ViewDidLoad 方法不保留变量



这是我的问题:

viewDidLoad方法中,我使用 NSUserDefaults 创建一个变量(如果是"第一次运行",我会创建它并用 NSNumber 填充它。然后我尝试在另一种方法中使用它,然后...无。它看起来像是空的。 有人可以帮助我吗?非常感谢

- (void)viewDidLoad {
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:@"seriesBool"]!=nil)
{
    seriesBool = [defaults objectForKey:@"seriesBool"];
}
else
{
    int i;
    seriesBool = [NSMutableArray arrayWithCapacity:9];
    for(i=0; i<9; i++)
    {
       [seriesBool addObject:[NSNumber numberWithBool:YES]];
    }
}

-(IBAction)toAction:(id)sender
{
NSLog(@"array: %@", seriesBool);
}

系列布尔是空的...

您必须设置如下属性

@property(nonatomic,retain) NSMutableArray * seriesBool;

并使用它

self.seriesBool = [NSMutableArray arrayWithCapacity:9];

 seriesBool = [[NSMutableArray alloc] initWithCapacity:9];

而不是

seriesBool = [NSMutableArray arrayWithCapacity:9];

你必须分配和分配对象

seriesBool = [[NSMutableArray alloc] init];
seriesBool = [defaults objectForKey:@"seriesBool"];

您需要首先学习内存管理的基础知识。基本上,那里发生的事情是,你没有保留系列布尔iVar。

看看这里: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/MemoryMgmt.html

尝试保留 iVar,或者更好的是,创建一个强/保留属性并使用访问器方法。

最新更新