简体   繁体   中英

iOS - resetting NSMutable Array causes crash

I have an NSMutableArray I'm trying to reload after an async call. The first time it loads like this:

self.sessionProcList = [NSMutableArray arrayWithArray:[result records]];

After the user does some interaction, the same line will be reached to reload the NSMutableArray. This causes the crash

Header file has:

@interface...
NSMutableArray *sessionProcList;
... }

@property (nonatomic, retain) NSMutableArray *sessionProcList;

Say you do:

NSMutableArray *a = [NSMutableArray arrayWithObject: [[NSObject alloc] init]];
NSObject *o = [a objectAtIndex: 0];
[a removeAllObjects];
[o description]; // *BOOM*

The above will [generally -- sometimes not but only by coincidence] crash because o has been deallocated by the time the description method is invoked.

If you have a reference to an object in an array, but have not retained said reference, then said object may be deallocated out from under you when you empty the array.

(And nonatomic vs. atomic is irrelevant.)

If I had to guess, I would say that elements in that array are being referenced from somewhere else. Resetting the array causes the items using the references to crash.

I would check your application for other variables, properties, or UI elements using those variables that have not been release before resetting it.

Because arrayWithArray is a convenience method it gets initialised with an autorelease flag.

You haven't mentioned what the crash / error message is but I am guessing your NSMutableArray is getting released before your second iteraction with it starts.

Try and retain the array for however long you need it with:

self.sessionProcList = [NSMutableArray arrayWithArray:[result records]];
[sessionProcList retain];

And then release it when you're done with it:

[sessionProcList release];

I hope it helps. Rog

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM