Objective-C Object gone due to memory management in NSMutableArray

203 views Asked by At

I have a problem regarding the memory management when adding objects to a NSMutableArray. Weird thing is that it's all working fine for the first 8 objects I add, but when adding a 9th, the application crashes when retrieving this object.

UploadStatus *status = [[UploadStatus alloc] initWithStatus:[NSString stringWithFormat:@"%@: %d", NSLocalizedString(@"uploadPictureSucceeded", @""), pic_id] 
                                                 andImageInProgress:nil 
                                                    imageForSuccess:nil 
                                                     imageForFailed:nil];
[self.delegate notify:status];
[status release];

This is being done on several places with different texts. But this object contains my status that I display in a UITableView.

In the notify method of the delegate I add the UploadStatus object to the NSMutableArray and I reload the UITableView that shows the objects inside that array.

The first 8 times I add a UploadStatus object to the array and reload the table, it shows correctly. But the 9th time I get the error [CFString retain]: message sent to deallocated instance 0x5c655c0. This error occurs when reloading the table in the cellForRowAtIndexPath method.

Weird thing is that it always shows that the objects inside the NSMutableArray are out of scope like in this screenshot:

enter image description here

Nevertheless if I fetch the item, convert it into the UploadStatus class and get the status from it, it all goes smoothly (for the first 8 objects).

Does anybody have a clue why it goes wrong after adding the 9th UploadStatus object to the NSMutableArray?

Thanks a lot for your help!

2

There are 2 answers

3
user1118321 On BEST ANSWER

The problem is with this code:

[NSString stringWithFormat:@"%@: %d", NSLocalizedString(@"uploadPictureSucceeded", @""), pic_id]

You aren't retaining the string, so it goes away on the next execution of the run loop. You're getting lucky with the first 8. They happen to not get overwritten for some reason, or possibly some other object is retaining them. But the 9th one isn't and you finally see the results of the mistake.

You need for the UploadStatus object to retain that string (and later release it).

6
Rob Napier On

I note that you're directly accessing your ivars in this block of code rather than using accessors. This is almost certainly the root of your problem (it is the #1 cause of memory management problems in ObjC). Switch to accessors and most of your memory management problems will go away.

You should also go ahead and run the static analyzer (Build>Analyze). It might shed light. The problem is likely not in the above code; it's somewhere that you're storing something, most likely in an an ivar.