开发者

initWithFormat not making much sense after 2 hours?

Being the 'newbie' I have been staring at the 'documentation and api reference' docs for 2 hours trying to figure out what I am doing wrong and my eyeballs are now bleeding. The following code keeps throwing 'yellow triangle' warning in xcode 4. (Format not a string literal and no format arguments)

I really don't know what I am doing ... yet, but I would like to understand why and I getting this warning and how to make it go away. Thanks for any h开发者_高级运维elp.

-(IBAction)saveZip:(id)sender
{
    zipCode = [[NSString alloc] initWithFormat:zipText.text];
    [zipText setText:zipCode];
    NSUserDefaults *zipDefault = [NSUserDefaults standardUserDefaults];
    [zipDefault setObject:zipCode forKey:@"ZipCode"];
}


You should use string literal for format in initWithFormat: method, not a string so your call should be corrected to:

zipCode = [[NSString alloc] initWithFormat:@"%@", zipText.text];

But in your example you don't need that method at all as you actually don't change the string, so next 'fix step" may be

zipCode = [zipText.text copy];

But that also leaves one problem unsolved - your previous zipCode value won't be deallocated and will just leak. If zipCode is an instance variable in your class declare a property for it:

// Class interface
@property (nonatomic, copy) NSString *zipCode;
// Class implementation
@synthesize zipCode;

That way you let compiler automatically synthesize setter and getter methods for you variable that will handle memory management for you.So now to change your iVar value you can use property:

self.zipCode = zipText.text;

P.S. and finally - don't forget to release your zipCode in dealloc method to avoid memory leaks


initWithFormat: expects a format string followed by a list of arguments that correspond to the format specifiers in your string. For example:

NSString *city = @"East Aurora";
NSString *state = @"NY";
NSInteger numericZip = 14052;
NSString *lastLineOfAddress = [[NSString alloc] initWithFormat:@"%@, %@ %d", city, state, numericZip];

In this example, lastLineOfAddress will reference the string @"East Aurora, NY 14052". There are three format specifiers in the format string. The first two format specifiers are %@, which can be a placeholder for any object type. %d is a placeholder for a decimal integer value. The three parameters that follow the format string correspond to these three format specifiers.

(I see that someone else has now posted a solid answer to your question, so I'll cut off my answer here.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜