简体   繁体   中英

Releasing an ivar with the Copy property

If I have a class

@interface Foo {
    NSString *temp;
}

@property(nonatomic, copy) NSString *temp;

@end

I understand that upon assignment, the old temp will get released and the new one will be assigned using temp = [newTemp copy] . And going by memory management rules, you are supposed to do [temp release] in the dealloc method of Foo, right?

What I don't understand is what happens if the setter was never used - you still have the [temp release] in the dealloc, so it's releasing something with a retain count of 0. Can someone clarify this for me?

There are two possibilities.

  1. Since you never set it, it's nil . Sending release to nil is just fine. So no problem there.

  2. Your init routine makes a default value for temp . Then it is a real object, and sending it release is also ok.

No problem all around! In neither case are you sending a message to an object with a retain count of 0.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM