将数组存储到NSUserDefaults中

时间:2016-07-04 13:18:57

标签: ios objective-c arrays nsuserdefaults

使用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旨在永久存储数据?一些提示?

3 个答案:

答案 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");
    }