NSMutable Array returning NULL when NSLog
So I have an NSMutable array that I populate in viewDidLoad and then I NSLog it and it returns NULL in the console... I have looked around on stack-overflow and the apple reference and cannot find a solution to my problem.
Heres the code I used:
//Populate array
-(void)populateArray{
[TextArray 开发者_运维技巧addObject:@"Text1"];
[TextArray addObject:@"Text2"];
[TextArray addObject:@"Text3"];
[TextArray addObject:@"Text4"];
[TextArray addObject:@"Text5"];
NSLog(@"%@",TextArray);
NSLog(@"%@",[TextArray objectAtIndex:1]);
}
-(void)viewDidLoad
{
TextArray = [[NSMutableArray alloc] init];
[self populateArray];
}
And in the .h file
NSMutableArray *TextArray;
Thanks in advanced! ~Matt
the code you posted does not contain enough information for us to provide a specific answer. chances are, the methods are not being called in the order you expect them (e.g. populateArray is called from another point before viewDidLoad).
some assertions should help diagnose this:
//Populate array
-(void)populateArray
{
assert(nil != self.textArray && "you need to create an array");
[self.textArray addObject:@"Text1"];
[self.textArray addObject:@"Text2"];
[self.textArray addObject:@"Text3"];
[self.textArray addObject:@"Text4"];
[self.textArray addObject:@"Text5"];
assert(5 == [self.textArray count] && "populateArray has been called twice or serious threading error");
NSLog(@"%@",textArray);
NSLog(@"%@",[textArray objectAtIndex:1]);
}
-(void)viewDidLoad
{
assert(nil == self.textArray && "you need to clear your array (e.g. in viewDidUnload) or check if it has already been populated");
self.textArray = [NSMutableArray array];
[self populateArray];
assert(5 == [self.textArray count] && "populateArray has been called twice or serious threading error");
}
lastly, if this array never changes, it's going to be much simpler to create this in your initializer rather than lazily. such an array will not require much memory, in case that was your concern.
Update the construct takes this form:
- (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle
{
self = [super initWithNibName:nibName bundle:nibBundle];
if (nil != self){
textArray = [[NSArray alloc] initWithObjects:@"Text1", @"Text2", @"Text3", @"Text4", @"Text5", nil];
// ...
}
return self;
}
lastly, viewDidLoad
may be certainly be called multiple times on the same instance. the system unloads (then lazily reloads) views in low memory conditions.
精彩评论