icespace
icespace

Reputation: 951

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 thing to do?

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

Upvotes: 0

Views: 207

Answers (1)

kennytm
kennytm

Reputation: 523184

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.

Upvotes: 6

Related Questions