NSMutableArray 在本地添加对象,但在下一个函数中访问时似乎会清除对象



所以基本上,我声明一个NSMutableArray,分配并在viewdidload中初始化它,调用一个将对象添加到数组的函数(我在添加对象后立即用NSLog验证),但是当下一个方法被调用并尝试访问NSMutableArray时,它会变为空白。

这是怎么回事?

@interface ViewController ()
{
    NSMutableArray * array;
}
@end
@implementation ViewController
@synthesize array;
- (void)viewDidLoad
{          
    [super viewDidLoad];
    array = [[NSMutableArray alloc] init];
    [self firstfunction];
    if (j.intValue == 1)
    {
        [self secondfunction];
    }
}
- (void)firstfunction
{
    //a bunch of stuff happens with a server
    [array addObject:object];   
    NSLog(@"There are %d in array",array.count);
    //** NSLOG RETURNS "THERE ARE 1 IN ARRAY" **//
    [tableView reloadData];
    //clean up code
    j = [[NSNumber alloc] initWithInt:1];
}
- (void)secondfunction
{
    NSLog(@"There are these many in the array now %d",array.count);
    //**NSLOG RETURNS:"There are these many in the array now 0"**//
}

提前谢谢。

请在第一个函数的末尾写下 [self secondfunction]。原因是,在填充数组之前,调用了第二个函数。

因为我认为您在某个异步块中具有服务器链接代码。所以在你得到结果之后你把它添加到数组中,但是在你得到结果并将其添加到数组之前执行secondFunction。

-(void)firstfunction{
   //a bunch of stuff happens with a server
   [array addObject:object];
   NSLog(@"There are %d in array",array.count);
   [tableView reloadData];
   [self secondfunction];
}
-(void)secondfunction{
   NSLog(@"There are these many in the array now %d",array.count)
   //**NSLOG RETURNS:"There are these many in the array now 0"**//
}

最新更新