Can't get an NSString ivar to accept a value from an array
I am storing some data (some floats, some strings) to a plist and then reading them back. When I read them back, I assign them to some ivars in my view c开发者_运维技巧ontroller. They are just ivars, not properties.
The floats take their values fine and I can NSLog
them and see that they are correct. But no matter what I try, I can't get my NSString ivars to take the string values.
Example: array positions 6 and 7 have the strings Portland, OR"
and "Pacific Daylight Time"
stored in them - read back from the plist into *array.
This:
cityName = [NSString stringWithFormat:@"", [array objectAtIndex:6]];
timeZoneName = [NSString stringWithFormat:@"", [array objectAtIndex:7]];
NSLog(@" >cityName from array = %@, and now the iVar is = %@", [array objectAtIndex:6], cityName);
NSLog(@" >timeZoneName from array = %@, and now the iVar is = %@", [array objectAtIndex:7], timeZoneName);
Results in this:
>cityName from array = Portland, OR, and now the iVar is =
>timeZoneName from array = Pacific Daylight Time, and now the iVar is =
I put a breakpoint at the end of the method where this happens and for both NSString
ivars, the little pop up message says, Invalid Summary.
cityName = [NSString stringWithFormat:@"%@", [array objectAtIndex:6]];
The mistake is that you've missed the format specifier. Specifically though, if the objects in the array are already strings, you can just assign them straight to the ivar:
cityName = [array objectAtIndex:6];
Be careful about object ownership though. You don't own the object returned by objectAtIndex:
so if you need to use this ivar in many different methods, obtain ownership by sending retain
, and relinquish ownership using release
. Alternatively if you choose to establish cityName
as a retaining or copying property of your class, use the dot-notation or accessor method:
self.cityName = [array objectAtIndex:6];
// or
[self setCityName:[array objectAtIndex:6]];
If the array contains NSString
instances there is no need to call +stringWithFormat:
. It is a waste of CPU cycles and undoes any potential optimizations related to immutable strings. Furthermore, relying upon the results of description
is never the right answer (though it is nigh unavoidable with NSStrings -- this is the one spot where you can rely on the result).
This (fixed):
cityName = [NSString stringWithFormat:@"%@", [array objectAtIndex:6]];
timeZoneName = [NSString stringWithFormat:@"%@", [array objectAtIndex:7]];
Could be:
cityName = [array objectAtIndex:6];
timeZoneName = [array objectAtIndex:7];
Copy it if you need to. As @dreamlax said, make sure you follow the memory management rules.
Use below
cityName = [NSString stringWithFormat:@"%@", [array objectAtIndex:6]];
You require to use %d or %i for integers and %@ is used for string objects.
精彩评论