使用NSUserDefaults永久存储我的数组时遇到了一个小问题。
我的ViewController.m的摘录
@property (strong, nonatomic) NSMutableArray *locationArray;
- (IBAction)onAddClick:(id)sender {
NSLog(@"onAddClick");
CLLocationDegrees lat = self.mapView.userLocation.location.coordinate.latitude;
CLLocationDegrees longi = self.mapView.userLocation.location.coordinate.longitude;
CLLocation *currentLocation = [[CLLocation alloc] initWithLatitude:lat longitude:longi];
[self.locationArray addObject:currentLocation];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:self.locationArray];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"locationData"];
[[NSUserDefaults standardUserDefaults] synchronize];
}
在我的LocationTableViewController.m中,我想要检索该数组:
NSData* data = [[NSUserDefaults standardUserDefaults] objectForKey:@"locationData"];
self.locationArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if (data != nil) {
NSLog(@"found data");
}
if (self.locationArray.count > 0) {
NSLog(@"found array");
}
当我不关闭应用程序时,一切正常,我可以从Userdefaults检索数据。关闭后,数据不再存在...我认为NSUserDefaults旨在永久存储数据?一些提示?
答案 0 :(得分:1)
我认为问题在于您归档包含CLLocation
对象的数组对象,NSUserDefault
可以保存某些类型的对象,如NSData, NSNumber, NSString, NSArray
,并且NSArray中包含的对象也应该是其中一种类型。
archivedDataWithRootObject
CLLocation
每个NSArray
对象NSArray
,意味着NSData
中包含select topic_name, avg(score)
from my_table
where event_date between '2016-03-01' AND '2016-03-31'
group by topic_name
,然后重试。
答案 1 :(得分:0)
我认为数组初始化应该在使用该数组之前完成,如:
self.locationArray = [[NSMutableArray alloc] init];
答案 2 :(得分:-2)
在从UserDefaults检索之前初始化locationArray。
NSData* data = [[NSUserDefaults standardUserDefaults] objectForKey:@"locationData"];
self.locationArray = [[NSMutableArray alloc]init];
self.locationArray = [NSKeyedUnarchiver unarchiveObjectWithData:data];
if (data != nil) {
NSLog(@"found data");
}
if (self.locationArray.count > 0) {
NSLog(@"found array");
}