NSUserDefaults 无法保存 NSMutableDictionary [英] NSUserDefaults fail to save NSMutableDictionary
问题描述
我正在尝试使用以下代码将 NSMutableDictionary 保存到 NSUserDefaults:
Iam trying to save NSMutableDictionary to NSUserDefaults with this code:
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 = "<Person: 0x1ed57e70>";
}' of class '__NSDictionaryM'. Note that dictionaries and arrays in property lists must also contain only property values.
并且 Person 类也有 NSCoding:
and also the Person Class have NSCoding:
Person.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
Person.m
@implementation Person
@synthesize name,email,phoneNumber,age,gender;
#pragma mark
#pragma mark NSCoder
- (void)encodeWithCoder:(NSCoder *)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)initWithCoder:(NSCoder *)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
知道为什么会这样吗?
推荐答案
对于什么类型的数据可以同步到 NSDictionary
中的 NSUserDefaults
有非常具体的限制.这些包括 NSString、NSNumber、NSData、NSArray 和 NSDictionary
.在存储在 NSUserDefaults
之前,使用您的 NSCoder
方法序列化为 NSData
(使用 NSKeyedArchiver
).
There are very specific restrictions as to what type of data can be synced to NSUserDefaults
within an NSDictionary
. These include NSString, NSNumber, NSData, NSArray and NSDictionary
. Use your NSCoder
methods to serialize to NSData
(using NSKeyedArchiver
) before storing in the NSUserDefaults
.
另外,看看这个
这篇关于NSUserDefaults 无法保存 NSMutableDictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!