user198725878
user198725878

Reputation: 6386

NSString variable: should it be released?

When we create NSString object, do I need to release it?

When I run the static analyser for my application, i get the following

NSString *dataStr=[[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];    
Method returns an Objective-C object with a +1 retain count (owning reference)

Upvotes: 0

Views: 194

Answers (4)

dreamlax
dreamlax

Reputation: 95315

The reason the static analyser says that is because your method's name does not imply that the caller of the method has ownership of the object you're returning. There are a few solutions:

  1. Modify your method's name so that it implies ownership of the returned object, i.e. these names imply ownership because they start with the word “new” or contain the word “copy”:

    • - (NSString *) newDataString
    • - (NSString *) copyDataString

    If you use method names like the above, that means that the caller of the method is responsible for sending the object a release message when it is done with it.

  2. Modify your method so that it relinquishes ownership of the object before returning it using the autorelease method:

    - (NSString *) dataString
    {
        NSString *tmp = [[NSString alloc] initWithFormat:@"%f", 2.444];
        return [tmp autorelease];
    }
    

    Remember, every alloc, copy or retain must be balanced with a release or autorelease (but not both!).

  3. Read the Cocoa Memory Management Rules. These rules are not optional, you must follow them. The rules are also very simple. After a bit of practice they will become second nature.

Upvotes: 3

Matthew Frederick
Matthew Frederick

Reputation: 22305

The magic words are alloc, copy, and retain: if any of them are used when the object is created or the property declared, you will need to release it.

Upvotes: 3

Ishu
Ishu

Reputation: 12787

Yes you need to release it. Every variable which having retain count must be release.

Upvotes: 1

jonmorgan
jonmorgan

Reputation: 2610

Yes, you need to release it. Generally, any time you create an object pointer calling alloc you will need to call release.

Upvotes: 1

Related Questions