2

我正在尝试使用以下代码将 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 = "<Person: 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)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

知道为什么会这样吗?

4

1 回答 1

4

对于可以NSUserDefaultsNSDictionary. 这些包括NSString, NSNumber, NSData, NSArray and NSDictionary. 在存储NSCoder到. NSData_NSKeyedArchiverNSUserDefaults

另外,看看这个

于 2013-01-11T16:56:49.477 回答