I'm trying to load an array from the NSUserDefaults
in an iPhone
application. I set things up with this code:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
self.myarray_1 = nil;
but then my application crashes at the following line:
self.myarray_1 = [[NSMutableArray alloc]
initWithArray: [defaults objectForKey:@"highscores"]];
with the error
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '-[NSCFString count]: unrecognized selector sent to instance 0x796c710'
How can I solve this?
The error message says that an instance of NSString
received a count
message, but obviously it does not respond to it (ie does not implement such a message). Most likely the message was intended for an NSArray
instance.
Did you accidentally save an NSString
instead of an NSArray
in your defaults for the key @"highscores"
? Maybe in one of your previous builds? To clear all user defaults, you could just delete the app from the simulator or your device and reinstall it.
Try this
self.myarray_1 = [[NSMutableArray alloc] initWithArray:(NSArray*)[defaults objectForKey:@"highscores"]];
and I am sure you have made variable myarray_1 as proparty of your this class.
The value in your app's defaults is a String, not an Array. You are probably setting the default to a string rather than an array elsewhere in your code. Look for where you're calling -[NSUserDefaults setObject:forKey:]
with the highscores
key as the second parameter. Either you are still passing in an NSString as the first argument, or you were at one point and it's still set in the app's preferences.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.