【问题标题】:NSUserDefaults nothing save when i NSLog it [duplicate]当我对它进行 NSLog 操作时,NSUserDefaults 什么也没有保存[重复]
【发布时间】:2013-09-20 13:16:27
【问题描述】:

我正在尝试将我的NSMutableArray 数据保存到NSUserDefaults,但是在我的日志中完成之后仍然是(null) 值。 我的代码有问题吗?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
NSUserDefaults*defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.FlipsideView.myMutableArray forKey:@"NSMutableArray"];
[defaults synchronize];
NSLog(@"tableview data: %@", self.FlipsideView.myMutableArray);
NSLog(@"tableview data: %@", [defaults objectForKey:@"NSMutableArray"]);
}

这是我的调试结果:

2013-09-20 15:10:08.914 Milosova[4033:a0b] tableview data: (null)
2013-09-20 15:10:08.915 Milosova[4033:a0b] tableview data: (null)

这是来自我的 ViewController 的代码,我在其中将一些数字放入 textFields:

- (void)counter:(id)sender{

double value1 = [litre.text doubleValue];
double value2 = [kilometer.text doubleValue];
double result = (value1 / value2) * 100;
self.display.text = [NSString stringWithFormat:@"%.2lf", result];
function*newCell = [[function alloc] initWithName:self.litre.text done:NO];
[self.flipsideView.myMutableArray addObject:newCell];
newCell = [[function alloc] initWithName:self.kilometer.text done:NO];
[self.flipsideView.myMutableArray addObject:newCell];
newCell = [[function alloc] initWithName:self.display.text done:NO];
[self.flipsideView.myMutableArray addObject:newCell];
[self.flipsideView.tableView reloadData];
}

这是我的功能代码:

-(id)initWithName:(NSString *)name done:(BOOL)done{
self = [super init];

if (self) {
    self.name = _name;
    self.done = _done;
}
return self;
}

我通过prepareForsegue方法放入tableView:

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([segue.identifier isEqualToString:@"route"]) {
    UINavigationController *navi = segue.destinationViewController;
    MainViewController*controller = [navi.viewControllers objectAtIndex:0];
    controller.flipsideView = self;

} }

【问题讨论】:

  • 您正在尝试将 nil 数据添加到字典中。
  • 不知道,告诉我们你是如何添加的,我们会看到的。
  • 在添加对象之前,您是否在某处分配了NSMutableArray?类似[[self flipsideView] setMyMutableArray:[NSMutableArray array]];
  • 我只是在 viewDidLoad 方法中的 tableViewController 中分配该数组。 { myMutableArray = [[NSMutableArray alloc] init] }
  • 我无法找到超过两周的时间。我是 xcode 的新手,所以任何帮助表示赞赏。

标签: ios nsmutablearray nsuserdefaults nslog


【解决方案1】:

正如 Desdenova 所指出的,您尝试添加的数组是 nil,因此您添加到用户默认值的内容当然也将是 nil。

您需要将有效的属性列表对象添加到用户默认值。 Nil 对象,或不是属性列表对象的对象将不会保存。

如果您认为 self.FlipsideView.myMutableArray 不应该为 nil,则需要跟踪创建和填充该数组的代码。

如果该属性被声明为 weak 或 unsafe_unretained 那是你的问题。它正在被释放。

【讨论】:

  • 属性 myMutableArray 是(非原子的,强的)。您是说这个属性吗?
  • 但是当我在 perepareForSegue 方法中使用 NSLog 时,myMutableArray 有 4 个对象。当我想将它存储到 NSUserDefaults 中时,怎么可能是空的?
【解决方案2】:

你的代码中还缺少一个你没有同步的东西NSUserDefaults尝试使用下面的代码行

[[NSUserDefaults standardUserDefaults] synchronize];

【讨论】:

  • 我有[默认同步];一样的?我忘记了,但还是空的
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-08
  • 1970-01-01
  • 1970-01-01
  • 2016-05-11
相关资源
最近更新 更多