-1

Possible Duplicate:
Saving UIColor to and loading from NSUserDefaults

I think to init user defaults, make NSDictionary, input data, and refisterDefaults. But this code has error.

//if UserFilter entry is nothing, create.
NSDictionary *defaultFilter = [NSDictionary dictionaryWithObject:[NSNumber numberWithInt:0] forKey:@"UserFilter"];
[userDefaults registerDefaults:defaultFilter];

//if UserBadgeColor entry is nothing, create.
UIColor *color = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
NSValue *valColor = [NSValue value:&color withObjCType:@encode(UIColor)];
NSDictionary *defaultBadgeColor = [NSDictionary dictionaryWithObject:valColor forKey:@"UserBadgeColor"];
[userDefaults registerDefaults:defaultBadgeColor];

Running, UserFilter part has no problem. But UserBadgeFilter part has error. Error line is last.

Thanks.

Community
  • 1
  • 1
Conao3
  • 171
  • 1
  • 3
  • 17
  • Last line has "EXC_BREAKPOINT(code=EXC_I386_BPT, subcode=0x0) – Conao3 Jan 05 '13 at 19:33
  • An object must be an instance of (or for collections a combination of instances of): NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary. Note that `NSValue` is not allowed. – zaph Jan 05 '13 at 19:53

1 Answers1

1

From the manual:

The NSUserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Booleans, and URLs. A default object 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. If you want to store any other type of object, you should typically archive it to create an instance of NSData.

But you can simply use NSData, so in your case:

UIColor *color = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
NSData* colorData= [NSKeyedArchiver archivedDataWithRootObject: color];
NSDictionary *defaultBadgeColor = [NSDictionary dictionaryWithObject: colorData forKey:@"UserBadgeColor"];
[userDefaults registerDefaults:defaultBadgeColor];

And when you read from the defaults, decode back the data to UIColor using NSKeyedUnarchiver.

Ramy Al Zuhouri
  • 21,580
  • 26
  • 105
  • 187