开发者

Should I release this NSString?

Guys: Please help. I have a utility class to return a NSString with encoding. Like this:

/*Get a NSString with chinese encoding*/
+(NSString*) getGBKString:(void *)buffer
{
  NSString* string = [[[NSString alloc] 
                      initWithBytes:buffer 
                        length:sizeof(buffer) 
                        encoding:kCFStringEncodingGB_18030_2000] 
                      autorelease];

  return string;
}

Here the autorelease is the right thi开发者_如何学运维ng to do?

If so, the method caller should call retain incase the NSString object is released?


Here the autorelease is the right thing to do?

Yes. Since the method does not contain +alloc/new/copy, to follow the Cocoa memory management rules, you should return an object with no ownership.

Alternatively, you could rename the method to +newGBKString: and remove the -autorelease, then the people knowing the convention will know the caller will gain the ownership.

If so, the method caller should call retain incase the NSString object is released?

The caller should -retain if it wants to keep the NSString.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜