【问题标题】:Store Array into NSUserDefaults将数组存储到 NSUserDefaults
【发布时间】: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


【解决方案1】:

我认为问题在于您归档包含CLLocation 对象的数组对象,NSUserDefault 可以保存某些类型的对象,例如NSData, NSNumber, NSString, NSArray,并且 NSArray 中包含的对象也应该是这些类型之一。

所以archivedDataWithRootObject 每个CLLocation 对象都指向NSArray,意味着NSArray 包含NSData,然后再试一次。

【讨论】:

    【解决方案2】:

    我认为数组初始化应该在使用该数组之前完成,例如:

    self.locationArray = [[NSMutableArray alloc] init];
    

    【讨论】:

      【解决方案3】:

      在从 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");
          }
      

      【讨论】:

      • 那没有用。
      • 而且一个数组可以有零个元素,所以检查self.locationArray.count > 0是错误的。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-19
      • 1970-01-01
      • 2013-09-25
      • 1970-01-01
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      相关资源
      最近更新 更多