Saturday, May 18, 2013

NSString initWithString example ios


[NSString initWithString]

Returns an NSString object initialized by copying the characters from another given string.
- (id)initWithString:(NSString *)aString
Parameters
aString
The string from which to copy characters. This value must not be nil.

Important: Raises an NSInvalidArgumentException if aString is nil.
Return Value of [NSString initWithString]
An NSString object initialized by copying the characters from aString. The returned object may be different from the original receiver.
Example of [NSString initWithString]
NSString *remainingStr = nil;
if (remaining > 1)
    remainingStr = [[NSString alloc] initWithFormat:@"You have %d left to go!", remaining];
else if (remaining == 1)
    remainingStr = [[NSString alloc] initWithString:@"You have 1 left to go!"];
else
    remainingStr = [[NSString alloc] initWithString:@"You have them all!"];

NSString *msg = [NSString stringWithFormat:@"Level complete! %@", remainingStr];

[remainingStr release];

[self displayMessage:msg];
Example of [NSString initWithString]
NSString* myString = [[NSString alloc] initWithString:@"Test"];
[myString release];
myString = someOtherString;
Example of [NSString initWithString]
- (id)initWithString:(NSString *)str
{
    self = [super init];
    if (self != nil) {
        if ([str _isStringLiteral] || [str _isImmutable]) {
            [self release];
            return [str retain];
        }
        ...
}