开发者

releasing object after return

开发者 https://www.devze.com 2023-01-04 05:35 出处:网络
I use an object to get some values with it and return this values. The values which will be returned are still in this object.

I use an object to get some values with it and return this values. The values which will be returned are still in this object. Heres the code:

    XMLErrorParser *xmlErrorParser = [XMLErrorParser alloc];
    [xmlErrorParser parseData: data];
    return xmlErrorPa开发者_StackOverflow社区rser.errors;

So how can i release the xmlErrorParser Object and return the values of it? Thanks.


Just return an auto-released version of the object errors holds.

Without giving us more details about what XMLErrorParser is, lets assume that errors holds some NSArray:

XMLErrorParser *xmlErrorParser = [[XMLErrorParser alloc] init];
[xmlErrorParser parseData: data];
NSArray *errors = [[xmlErrorParser.errors retain] autorelease];
[xmlErrorParser release];
return errors;

(Note that you were missing the initialization for the error parser object.)


XMLErrorParser *xmlErrorParser = [[XMLErrorParser alloc] init];
[xmlErrorParser parseData: data];
return [xmlErrorParser autorelease].errors;

or better

XMLErrorParser *xmlErrorParser = [[[XMLErrorParser alloc] init] autorelease];
[xmlErrorParser parseData: data];
return xmlErrorParser.errors;


That's what autorelease is for (could it be that you forgot init?):

XMLErrorParser *xmlErrorParser = [[[XMLErrorParser alloc] init] autorelease];
[xmlErrorParser parseData: data];
return xmlErrorParser.errors;

Read the Memory Management Guide for Cocoa.


Depending on the purpose of your method, you might have to retain xmlErrorParser.errors as well.


I suppose parseData is your initializer, In that case you can use the autorelease message to let the innermost autorelease pool know that you no longer need the object.

Example:

XMLErrorParser *xmlErrorParser = [XMLErrorParser alloc];
[[xmlErrorParser parseData: data] autorelease];
return xmlErrorParser.errors;

I advise you explicitly retain the errors property as well, otherwise you can lose track of it. Rule of thumb, release and autorelease calls together must match the number of retains in order to dealloc an object.


How about - autorelease?

0

精彩评论

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