I am unable to release NSMutableArray that I created in a method.
SqliteData *s = [SqliteData alloc];
items = [NSArray alloc];
items = [s getItems:parent];
[s release];
IN SQLITeDATA 开发者_如何转开发class
-(NSMutableArray *)getItems:(NSString *)parent
{
NSMutableArray *items = [[[NSMutableArray alloc] init]autorelease];
return items
}
The app crashes, if I remove the autorelease it works fine.
The correct version is :
SqliteData *s = [[SqliteData alloc] init];
items = [[s getItems:parent] retain];
[s release];
Which is similar, but less optimized, to :
SqliteData *s = [[[SqliteData alloc] init] autorelease];
items = [[s getItems:parent] retain];
Beware about memory leaks :
SqliteData *s = [SqliteData alloc];
items = [NSArray alloc]; // memory leak there!
items = [s getItems:parent];
[s release];
You are leaking memory, since your replace newly allocated items
address with another.
And alloc
without init
is a non-sense. (you are allocating memory, but not initialized it!)
You're overwriting first
items
with a different value on next line. You don't need thatalloc
first — it does nothing.It's invalid to use
alloc
withoutinit
. Use[[foo alloc] init]
or[foo new]
.Autoreleased objects are only temporary (until end of life of current pool, which is usually life of thread or callback — don't expect object will survive much longer than duration of function it's in). You need to
retain
them.
精彩评论