0
votes

My question looks like a dozen ones about releasing properties, but I can't find the exact answer i'm searching for.

When a property is declared with retain :

@property (nonatomic, retain) NSString * myString;

then

@synthesize myString;

It generates getters and setters with retaining and releasing operations. Okay.

Of course, property must be released in dealloc.

-(void)dealloc {
    [myString release];
    myString = nil;
    [super dealloc];
}

So that's clean.

But what if i never use myString ? Is it pre-initialised ? My opinion is the myString retain-count would be 0. But releasing myString in dealloc would decrease it and make the application crash ? But it does not crash !

Is a cleaner way to release it like ?

if(myString != nil) {
    [myString release];
    myString = nil;
}
4

4 Answers

2
votes

The key thing you are missing is that you can send messages to nil. So no, your latter approach is not cleaner, just unnecessary.

If you never use myString, it's not initialized to anything. It remains nil. When you release it, you are effectively doing [nil release] - which doesn't actually do anything. Hence no crash.

1
votes

There is no need to check wether it is nil. If you send the release to a nil object nothing happens, so why check.

When an instance of object is created the property will be set to nil unless you initialize it in any of the init methods.

It not the same with variables you create in a method, they could point to invalid memory. Thus setting these to nil is the safe way. This is not needed for properties.

1
votes

You can send release messages to nil objects in objective-c this way nothing happens. I mean the application wont crash. The idea behind setting objects to nil comes handy when an object is used in multithreaded environment since with multiple threads you can't always guarantee that an instance variable will only be read before it's released.

0
votes

if you are using @property(retain/copy) & @synthesize there is no need to check for nil. It won't crash or throw EXC_BAD_ACCESS.

Otherwise, if you are not using that, you have to check whether the variable is nil or not, or it will crash if the variable is nil.