Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

When releasing objects that might have been retained during the app's lifetime, how do you check if the object really exists and prevent releasing a nil object?

Here's how I'm doing it:

- (void)dealloc{
    if(account_)
        [account_ release];
    account_ = nil;
    [super dealloc];
}
share|improve this question

1 Answer

up vote 6 down vote accepted
- (void)dealloc{
    if(account_)

You don't need to do this. Objective-C ignores attempts to call methods on nil objects. So you call release and nothing will happen if its already nil

        [account_ release];
    account_ = nil;

Your object is being destroyed, there isn't a whole lot of point in setting values to nil

    [super dealloc];
}
share|improve this answer
What happens if the object has already been released but the reference, for some reason, isn't nil? It has happened to me before, I suppose something wrong I made along the way? The error I get is along the lines of "Deallocated reference cannot be released again." – Solivagant Apr 15 '12 at 7:42
1  
@Solivagant, you should set the reference to be nil after you release it, unless the variable is going out of scope anyways. (Actually, to make it easier you should use the ARC feature in the newest versions of XCode. It takes care of release/retain for you automatically) – Winston Ewert Apr 15 '12 at 12:50

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.