So I had this code, and it did not work:
for (NSDictionary *item in data){
[self.resultsArray addObject:item];
}
self.resultsArray is nil. But then I changed it to this:
NSMutableArray *myDataArray = [[NSMutableArray alloc] init];
for (NSDictionary *item in data){
[myDataArray addObject:item];
}
self.resultsArray = myDataArray;
[myDataArray release];
and now it worked. self.resultsArray is now populated
So I’m a beginner in Objective C and I was wondering why can I not just directly use it in the property’s addObject. Why did I have to create another mutable array, populate it, assign it to the resultsArray property and release the mutable array I made?
Thanks in advance!
EDIT: Also, in a lot of books I’ve been working on, this is done a lot.
simple answer
You didn’t initialize
self.resultArraybefore adding objects to it. It is just a pointer to the value which is nil until youallocit.self.resultArray = [[NSMutableArray alloc] init];before adding objects to it will solve the issue.However, this way of alloc’ing will create a memory leak, therefore it is not shown in books and examples. Memory leak can happen if the
self.resultArrayproperty is marked asretainand by calling alloc it will be retained 2 times.