Question

I declared a NSMutableArray in the header-file with:

NSMutableArray *myMuArr;

and

@property (nonatomic, retain) NSMutableArray *myMuArr;

In the .m file I've got a delegate from an other class:

-(void)didGrabData:(NSArray*)theArray {
self.myMuArr = [[[NSMutableArray alloc] initWithArray:myMuArr]retain];
}

If I want to access the self.myMuArr in cellForRowAtIndexPath it's empty (I checked the retain count of the array and it's 0)

What am I doing wrong?

Of course it's released in the dealloc, no where else.

I would be very thankfull for any help :0)

Was it helpful?

Solution

I don't think you understand when to retain and release. Take a look at this SO question and answer. Read it thru and understand it and the read the articles it links to. It will help you a lot. It is essential to understand this on the iPhone.

Your array is getting retained 3 times, but you only needed one: (1) When you call alloc/init, you get an array that you own (it is retained). (2) When you called retain, that's an extra retain. (3) Your setter self.myMuArr was defined to retain in the @property, so when you assign the pointer using the setter method it gets retained again.

You commonly see code use these two techniques, both are correct:

-(void)didGrabData:(NSArray*)theArray {
   NSMutableArray *arr = [[NSMutableArray alloc] initWithObjects:obj1, obj2, nil];
   self.myMutArr = arr;
   [arr release];       
}

Or using arrayWithObjects, which gives you an autoreleased array that you need to retain if you want to take ownership of its memory space and keep it around. Your setter will do that:

-(void)didGrabData:(NSArray*)theArray {
   self.myMutArr = [NSMutableArray arrayWithObjects:obj1, obj2, nil];
}

OTHER TIPS

You should end up with a retain count of 3 if it wasn't for the fact that you try to initialize the array with the content of itself before it exists. Try replacing this line of code:

self.myMuArr = [[[NSMutableArray alloc] initWithArray:myMuArr]retain];

with this line:

self.myMuArr = [NSMutableArray arrayWithArray:theArray];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top