我正在尝试使用此代码将 NSMutableDictionary 保存到 NSUserDefaults:
NSUserDefaults *def = [NSUserDefaults standardUserDefaults];
NSMutableDictionary *repositoryData = [[NSMutableDictionary alloc] init];
[repositoryData setObject:personData forKey"persondata"];
[def setObject:repositoryData forKey"kUserRepository"];
[def synchronize];
[repositoryData removeAllObjects];
[repositoryData release];
但是我收到了这个消息:
[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '{
persondata = "<erson: 0x1ed57e70>";
}' of class '__NSDictionaryM'. Note that dictionaries and arrays in property lists must also contain only property values.
而且 Person 类也有 NSCoding:
人.h
@interface Person : NSObject <NSCoding> {
NSString *name;
NSString *email;
NSString *phoneNumber;
NSString *gender;
int age;
}
@property (nonatomic, retain) NSString *name;
@property (nonatomic, retain) NSString *email;
@property (nonatomic, retain) NSString *phoneNumber;
@property (nonatomic, retain) NSString *gender;
@property (assign) int age;
@end
人.m
@implementation Person
@synthesize name,email,phoneNumber,age,gender;
#pragma mark
#pragma mark NSCoder
- (void)encodeWithCoderNSCoder *)encoder{
[encoder encodeObject:self.name forKey"username"];
[encoder encodeObject:self.email forKey"useremail"];
[encoder encodeObject:self.phoneNumber forKey"userphonenumber"];
[encoder encodeObject:self.gender forKey"usergender"];
[encoder encodeInt:self.age forKey"userage"];
}
- (id)initWithCoderNSCoder *)decoder {
if(self = [super init]){
self.name = [decoder decodeObjectForKey"username"];
self.email = [decoder decodeObjectForKey"useremail"];
self.phoneNumber = [decoder decodeObjectForKey"userphonenumber"];
self.gender = [decoder decodeObjectForKey:@"usergender"];
self.age = [decoder decodeIntForKey:@"userage"];
}
return self;
}
@end
知道为什么会这样吗?
Best Answer-推荐答案 strong>
对于什么类型的数据可以同步到 NSDictionary 中的 NSUserDefaults 有非常具体的限制。这些包括 NSString、NSNumber、NSData、NSArray 和 NSDictionary 。在存储到 NSUserDefaults 之前,使用您的 NSCoder 方法序列化为 NSData (使用 NSKeyedArchiver )。
另外,看看 this
关于iphone - NSUserDefaults 无法保存 NSMutableDictionary,我们在Stack Overflow上找到一个类似的问题:
https://stackoverflow.com/questions/14282892/
|