【发布时间】:2016-07-04 13:18:57
【问题描述】:
我在使用 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 旨在永久存储数据?一些提示?
【问题讨论】:
-
在从 UserDefaults 中检索 locationArray 之前对其进行初始化。或打印 [NSKeyedUnarchiver unarchiveObjectWithData:data];检查数组是否存在
-
你应该使用
NSUserDefaults在视图控制器之间传递数据吗? -
我尝试将数组放入 NSUserDefault。我可以轻松插入和获取。
标签: ios objective-c arrays nsuserdefaults