I have declared a property NSMutableArray in the header file. Then I alloc, init it in the viewDidLoad method. But when I try to add an object to the array in a different method it keeps returning (null). Am I doing some obvious mistake? Please ask if you want to see some more code.
.h
@property (strong, nonatomic) NSMutableArray *myList;
.m
- (void)viewDidLoad
{
self.dataController = [[DataController alloc]init];
self.myList = [[NSMutableArray alloc] init];
[super viewDidLoad];
}
[...]
NSDictionary *myObject = [self.dataController.objectList objectAtIndex:r];
[[cell textLabel]setText:[myObject objectForKey:@"title"]];
[self.myList addObject:myObject];
NSLog(@"myList %@",self.myList);
NSLog(@"myObject %@",myObject);
The output prints myObject but self.myList keeps returning (null). Appreciate all help!
Edit: Fixed, thank you for your answers!
3 Answers 3
Not sure where you are using this array. If you have to use this array before viewDidLoad
is called, you can do it as,
NSDictionary *myObject = [self.dataController.objectList objectAtIndex:r];
[[cell textLabel]setText:[myObject objectForKey:@"title"]];
if (!self.myList)
self.myList = [[NSMutableArray alloc] init];//for the first time, this will initialize
[self.myList addObject:myObject];
Since you are using [cell textLabel]
I am assuming that you are doing this in one of the table view delegates. In that case check if you are setting self.myList = nil;
any where in the class.
5 Comments
myObject
. It could be that he is setting dataController
from previous class itself and initialization part for dataController
is not called while executing this. But I think you are correct due to the usage of [cell textLabel]
which should be done in cellForRowAtIndexpath
. That should have been called after viewDidLoad
. But in any case he has to add more info to his question.myObject
in init
as well, but didn't realize / didn't mention it.In your posted code i see no error. Set a breakpoint and look if the code where you init the array is called first.
Comments
I bet that viewDidLoad hasn't been called yet when the NSLogs are execute.
To ensure that the array has been initialized, try putting the initialization in your init method.
init
instead.