开发者

How am I meant to release an array returned from a class method?

I have a section of my code which calls a method returning an NSMutableArray like so:

+(NSMutableArray *)method {

NSMutableArray *rgb = [[NSMutableArray alloc] initWithObjects:....., nil];

    return rgb;

}

It gives me a leak every time it's called. Putting [rgb release]; after retu开发者_如何学Gorn doesn't appear to work. Putting it before return makes my app crash. Also putting in an autorelease makes my app crash. Suggestions?


+(NSMutableArray *)method {
    NSMutableArray *rgb = [[NSMutableArray alloc] initWithObjects:....., nil];
    return [rgb autorelease];
}

Alternatively:

+(NSMutableArray *)method {
    NSMutableArray *rgb = [NSMutableArray arrayWithObjects:....., nil];
    return rgb;
}

IF this still crashes, then the problem is most likely outside of that method, not within.


But this gives me a leak every time it's called. Putting a [rgb release]; after return doesn't appear to work. putting it before return makes my app crash. Also putting in an autorelease makes my app crash. Suggestions?

You need to read the Cocoa Memory Management Guidelines. It makes it quite clear that such a method as that must autorelease the returned object:

+(NSMutableArray *)method {
    NSMutableArray *rgb = [[NSMutableArray alloc] initWithObjects:....., nil];

    return [rgb autorelease];
}

Or, alternatively:

+(NSMutableArray *)method {
    NSMutableArray *rgb = [NSMutableArray arrayWithObjects:....., nil];

    return rgb;
}

An over-retain (like in your code) will not cause a crash (at least not until you run out of memory). If you have a crash, it is most likely because your are mismanaging memory in other ways.

Try using Build and Analyze and fixing all of the issues it identifies. If it still crashes, post the backtrace of the crash if you can't figure out why.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜