2
蔭努力的NSMutableDictionary保存到NSUserDefaults的與此代碼:NSUserDefaults的無法保存的NSMutableDictionary
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:
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'不能,除非他們鍵'NSString's保存到用戶的默認值。 'NSDictionary'可以使用其他類作爲鍵,但如果你這樣做,那麼你不能將它保存爲用戶默認值。 –