Saturday, May 18, 2013

NSString initWithFormat example ios


[NSString initWithFormat]

Returns an NSString object initialized by using a given format string as a template into which the remaining argument values are substituted.
- (id)initWithFormat:(NSString *)format ...
Parameters
format
A format string. See “Formatting String Objects” for examples of how to use this method, and “String Format Specifiers” for a list of format specifiers. This value must not be nil.
A comma-separated list of arguments to substitute into format.
Return Value of [NSString initWithFormat]
An NSString object initialized by using format as a template into which the remaining argument values are substituted according to the canonical locale. The returned object may be different from the original receiver.
Discussion of [NSString initWithFormat]
Invokes initWithFormat:locale:arguments: with nil as the locale, hence using the canonical locale to format numbers. This is useful, for example, if you want to produce "non-localized" formatting which needs to be written out to files and parsed back later.
Example of [NSString initWithFormat]
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 initWithFormat]
@interface NSString (NSArrayFormatExtension)

+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments;

@end

@implementation NSString (NSArrayFormatExtension)

+ (id)stringWithFormat:(NSString *)format array:(NSArray*) arguments;
{
    char *argList = (char *)malloc(sizeof(NSString *) * [arguments count]);
    [arguments getObjects:(id *)argList];
    NSString* result = [[[NSString alloc] initWithFormat:format arguments:argList] autorelease];
    free(argList);
    return result; // (Quinn) Should be autoreleased to obey Cocoa convention
}

@end
Example of [NSString initWithFormat]
+(NSString*) getBaseURL {
        NSUserDefaults *userSettings = [NSUserDefaults standardUserDefaults]; 
        NSString* host = [userSettings stringForKey:@"host"];
        NSString* port = [userSettings stringForKey:@"port"];
        NSString* baseURL = [[NSString alloc] initWithFormat: @"http://%@:%@", host, port];
        return baseURL;
    }