Crystal
Crystal

Reputation: 29448

Memory allocation / release for NSString

I have a class that adopts the MKAnnotation protocol. Along with the two "title and "subtitle" methods to implement, I wanted to add two NSStrings, one to represent each line in a typical US address. For example:

addressLine1 = 123 street
addressline2 = northridge, ca 91326

My subtitle method currently looks like:

- (NSString *)subtitle {
    NSMutableString * ret = [NSMutableString stringWithCapacity:kDefaultStringCapacity];
    if (streetAddress) {
        [ret appendString:streetAddress];
        addressLine1 = [[NSString alloc] initWithFormat:streetAddress];
    }
    ... more code

When would I release addressLine1? Because it is a property that I declared with (nonatomic, retain), I already released it in my dealloc method. Or am I to use a class method or autorelease the string? Thanks.

Upvotes: 1

Views: 693

Answers (2)

Deepak Danduprolu
Deepak Danduprolu

Reputation: 44633

If you autorelease address1, you will lose ownership on the object and without any other owners, it will get deallocated. You would need to autorelease it if you were doing,

self.address1 = [[NSString alloc] initWithString:streetAddress];

which is wrong as you would've taken ownership twice and relinquished it only once in the dealloc method. Right way would've been,

self.address1 = [[[NSString alloc] initWithString:streetAddress] autorelease];

The direct assignment above works only if it were to be assigned a value once. If it is to be assigned again, you would lose the reference to the earlier reference and your application will leak. So it would be good process to use the property accessors here which would ensure that the older values are deallocated.

Another thing with strings is that you would copy them as you wouldn't want them to mutate after assignment so the property should be declared as @property (nonatomic, copy) rather than what it is now.

Upvotes: 3

csano
csano

Reputation: 13676

If your property is (nonatomic, retain), then you're going to leak the addressLine1 resource if you don't explicitly release it. I'd release it as soon as you're done with it. The property should then be released in your dealloc method as you are currently doing.

Somewhat unrelated to the question, but still related, is that anytime you have an object that implements the NSCopying protocol, such as NSString in this case, you should use copy instead of retain. Here's a SO question that provides some great information.

Upvotes: 2

Related Questions