在我的头文件中我有:
@property (nonatomic, retain) NSMutableArray * array1;
在我的 initWithNibName
方法中我有:
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
self.array1 = [[NSMutableArray alloc] initWithObjects:@"test", nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DoUpdateLabel:) name:@"DoUpdateLabel" object:nil];
}
return self;
}
DoUpdateLable
方法对数组进行一些更新(添加一些项目)。一旦完成并且 ViewDidLoad 执行,我的数组就会消失并变为 null,这很烦人,因为我想将它加载到 TableView 中。
这是 DoUpdateLable
方法的简化版本。由于实际方法包含大量 JSON 解析和 URL 请求,我不得不将其缩减:
-(void)DoUpdateLabel:(NSNotification *) notification
{
int count = 0;
while(count < 59)
{
NSString * currentpatname = @"test1";
if(![currentpatname isEqualToString:@""])
{
[self.array1 addObject:currentpatname];
NSLog(@"array: %@", self.array1);
}
count++;
}
NSLog(@"final array: %@", self.array1);
}
我有点不明白为什么它没有被保留。任何帮助将不胜感激!
谢谢!
最佳答案
查看您更新后的问题,您正在以 //Custom initialization
开头的范围内设置该数组。但是您没有注意到的是 viewDidLoad
实际上是在这一行调用的:
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
这意味着您的数组在 viewDidLoad 中仍然为 nil,因此 DoUpdateLabel
我建议改为在 -viewDidLoad
中初始化该数组,您将看到您正在寻找的结果。
关于iphone - NSMutableArray 在 ViewDidLoad 之前被释放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18700979/