开发者

Memory allocation / release for NSString

开发者 https://www.devze.com 2023-03-11 20:17 出处:网络
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 addres

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.


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.


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.

0

精彩评论

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