NSUserDefaults saves more than just NSArray types. As explained in the NSUserDefaults Class Reference Overview, "A defaults value must be a property list, that is, an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary." It goes on to state, "If you want to store any other type of object, you should typically archive it to create an instance of NSData. For more details, see User Defaults Programming Topics for Cocoa."I know NSUserDefaults only saves NSArrays. How can I convert and my structure?
NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"HighScore.archive"];
BOOL result = [NSKeyedArchiver archiveRootObject:highScoresArraytoFile:archivePath];
NSString *archivePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"HighScore.archive"];
if ((highScoresArray = [NSKeyedUnarchiver unarchiveObjectWithFile:archivePath]) == nil) {
highScoresArray = [[NSMutableArray alloc] init];
}
@interface UserHighScore : NSObject <NSCoding> {
NSString *name;
NSString *drink;
NSNumber *score;
}
@implementation
-(void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:name forKey:@"Name"];
[encoder encodeObject:drink forKey:@"Drink"];
[encoder encodeObject:score forKey:@"Score"];
}
-(id)initWithCoder:(NSCoder *)decoder
{
if (self=[super init]){
name = [decoder decodeObjectForKey:@"Name"];
drink = [decoder decodeObjectForKey:@"Drink"];
score = [decoder decodeObjectForKey:@"Score"];
}
return self;
}
Which string? Can you give us more details of the error and where this is occurring? Is this when you are trying to add your single UserHighScore object to NSUserDefaults?I have tried to make just one custom object without putting it inside an array and in the debugger it says the string is invalid.
Which string? Can you give us more details of the error and where this is occurring? Is this when you are trying to add your single UserHighScore object to NSUserDefaults?
P.S. Also, please use the [ CODE ][ /CODE ] tags (remove the spaces) to enclose code snippets. These tags are accessible via the # icon in the toolbar.
You need to retain the objects from decodeObjectForKey if assigning it directly to a variable. If you're using properties (which you should) then you don't need to.