【问题标题】:How to Input UIColor to User defaults? [duplicate]如何将 UIColor 输入到用户默认值? [复制]
【发布时间】:2013-01-05 19:30:42
【问题描述】:

可能重复:
Saving UIColor to and loading from NSUserDefaults

我想初始化用户默认值、创建 NSDictionary、输入数据和 refisterDefaults。 但是这段代码有错误。

//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];

运行中,UserFilter 部分没有问题。但 UserBadgeFilter 部分有错误。 错误行在最后。

谢谢。

【问题讨论】:

  • 最后一行有“EXC_BREAKPOINT(code=EXC_I386_BPT, subcode=0x0)
  • 对象必须是以下实例(或集合实例的组合):NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary。请注意,NSValue 是不允许的。

标签: iphone objective-c xcode nsuserdefaults uicolor


【解决方案1】:

来自手册:

NSUserDefaults 类提供了方便的方法来访问常用类型,例如浮点数、双精度数、整数、布尔值和 URL。默认对象必须是一个属性列表,即以下实例(或集合实例的组合):NSData、NSString、NSNumber、NSDate、NSArray 或 NSDictionary。如果要存储任何其他类型的对象,通常应该将其归档以创建 NSData 的实例。

但你可以简单地使用 NSData,所以在你的情况下:

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];

当您从默认值中读取数据时,使用 NSKeyedUnarchiver 将数据解码回 UIColor。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-02
    • 2014-04-19
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    相关资源
    最近更新 更多