Mysterious loss of memory for global var?
In my code, I create a global variable (with no counterpart in the .h file) called Events. This is an NSMutableArray. It is only ever accessed by the class it is defined in.
When "viewDidLoad" gets called, my code does a number of things: First of all, it initializes Events. Then开发者_如何学Go, it creates 7 NSMutableArrays, and adds those to the Events object.
viewDIdLoad continues to do some UI setup, by creating allot of buttons and making sure they are put into another NSMutable array for tracking.
The Events object works fine and dandy, up until viewDidLoad finishes executing. If I press one of the generated buttons, and that button tries to access Events, the system crashed.
I did a ton of debugging trying to figure out what goes wrong, and I have narrowed it down to this:
Some time after my code is finished, Events gets dropped completely. I tracked it tot he end of my function, and at that end, it still had all seven NSMutableArrays.
Once it reached the end of my function, I hit the continue button, and placed a breakpoint just before the place where the generated buttons re-access the Events var. At THAT location, Events is completely empty.
Right now, for simplicity's sake, I am not doing any autorelase or retain commands. There is ONE release command for a variable defined in one of the several methods viewDidLoad calls.
Can anyone please tell me how to stop Events from being unloaded? Thankyou :)
It sounds like you are doing something like Events = [NSMutableArray array];
. That creates an autoreleased instance of NSMutableArray, which will be automatically disposed of sometime after your function returns.
Instead, you would want to do Events = [[NSMutableArray alloc] init];
to create an instance that is not autoreleased, or Events = [[NSMutableArray array] retain];
to retain the autoreleased instance. Either way the system will know that you are still using the object and therefore won't dispose of it.
You didn't post your code, but my guess is that you simply allocated the array via [NSMutableArray array]
, didn't you ? Well, the array is autoreleased sometime after the flow leaves the method in which you've created the array. To prevent that, you simply need to retain
the array.
精彩评论