当我在NSUserDefaults
中保存产品数组(这是一个自定义对象),并从NSUserDefaults
检索数组时,它会返回随机数组。当我检查返回的数组是否包含添加的产品时,它总是失败。这是我的代码:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *data = [defaults objectForKey:@"MY_FAV_PROD"];
NSArray *myFavArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSMutableArray *array = [[NSMutableArray alloc] initWithArray:myFavArray];
if(myFavArray.count || array.count) {
if([array containsObject:self.product]) {
[array removeObject:self.product];
myFavArray = nil;
myFavArray = [myFavArray copy];
data = [NSKeyedArchiver archivedDataWithRootObject:myFavArray];
[defaults setObject:data forKey:@"MY_FAV_PROD"];
[defaults synchronize];
[self addButton:@"UnFilled"];
}
else {
[array addObject:self.product];
myFavArray = nil;
myFavArray = [array copy];
data = [NSKeyedArchiver archivedDataWithRootObject:myFavArray];
[defaults setObject:data forKey:@"MY_FAV_PROD"];
[defaults synchronize];
[self addButton:@"Filled"];
}
}
else {
NSArray *firstObj = [[NSArray alloc] initWithObjects:self.product, nil];
data = [NSKeyedArchiver archivedDataWithRootObject:firstObj];
[defaults setObject:data forKey:@"MY_FAV_PROD"];
[defaults synchronize];
[self addButton:@"Filled"];
}
data = [defaults objectForKey:@"MY_FAV_PROD"];
myFavArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
NSLog(@"%@",myFavArray);
请帮忙