Search code examples
iospropertiesnsmutablearrayreturn-valuesetting

NSMutableArray adds object locally, but seems to clear when accessed in the next function


So basically, I declare an NSMutableArray, alloc and init it in the viewdidload, call a function that adds an object to the array (which I verify with an NSLog right after its added), but then when the next method is called and tries to access the NSMutableArray— it goes blank.

What is going on here?

@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"**//
}

Thanks in advance.


Solution

  • Please write [self secondfunction]; at the end of first function. Reason is, before the array is filled your second function is called.