我正在尝试将数组保存到NSUserDefaults
. 我读到我必须使用编码器和解码器,但我仍然得到同样的错误
*** -[NSUserDefaults setObject:forKey:]: Attempt to insert non-property value '(
"<Item: 0x1e86e380>",
"<Item: 0x1e86fd60>",
"<Item: 0x1e86fda0>",
"<Item: 0x1e86fde0>",
"<Item: 0x1e86fe10>"
)' of class '__NSArrayM'. Note that dictionaries and arrays in property lists must also contain only property values.
[unknown][unknown][unknown][unknown][unknown](gdb)
为什么??
这是我的代码:
这是我的模型。它有NSStrings
,NSNumbers
和NSMutableArrays
:
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject: self.title forKey:@"title"];
[encoder encodeObject: self.desc forKey:@"desc"];
[encoder encodeObject: (NSNumber*) self.day forKey:@"day"];
[encoder encodeObject: self.images forKey:@"images"];
}
- (id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if( self != nil )
{
self.title = [decoder decodeObjectForKey: @"title"];
self.desc = [decoder decodeObjectForKey: @"desc"];
self.day = [decoder decodeObjectForKey: @"day"];
self.images = [decoder decodeObjectForKey: @"images"];
}
return self;
}
这是在 AppDelegate 的DidFinishLaunching
方法中:
if([[NSUserDefaults standardUserDefaults] objectForKey:@"savedData"] == nil)
{
items = [[NSMutableArray alloc] init];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"items" ofType:@"json"];
NSString *contents = [NSString stringWithContentsOfFile: filePath encoding: NSUTF8StringEncoding error: nil];
SBJsonParser *jsonParser = [[SBJsonParser alloc] init];
NSMutableDictionary *json = [jsonParser objectWithString: contents];
jsonParser = nil;
items = json[@"item"];
for(NSDictionary *itemDict in items)
{
Item *item = [[Item alloc] init];
item.title = [itemDict valueForKey:@"title"];
item.desc = [itemDict valueForKey:@"description"];
item.day = [itemDict valueForKey:@"day"];
item.images = [itemDict valueForKey: @"images"];
[items addObject: item];
}
}
else
{
NSData *decodedObject = [userDefault objectForKey: [NSString stringWithFormat:@"savedData"]];
NSArray *decodedArray =[NSKeyedUnarchiver unarchiveObjectWithData: decodedObject];
items = [decodedArray mutableCopy];
}
我有这个AppWillTerminate
:
userDefault = [NSUserDefaults standardUserDefaults];
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject: items];
[userDefault setObject: encodedObject forKey:[NSString stringWithFormat:@"savedData"]];