1

I've read that you should set delegate to nil in dealloc. I noticed it is doing it in init, is this ok or should you do the same in the dealloc?

"This is subtle one but handy one. If you're passing yourself as a delegate to another object, reset that object's delegate before you dealloc."

file.h

@interface TestService : NSObject
{
    NSObject <TestServiceDelegate> *m_delegate;
}

@property (nonatomic, assign) NSObject <TestServiceDelegate> *delegate;

file.m

 @synthesize delegate=m_delegate;

    - (id)init
    {
        if (self = [super init])
        {        
            m_delegate = nil;
        }

        return self;
    }

    - (void)dealloc

    {
         [super dealloc];
    }
Mike Flynn
  • 22,342
  • 54
  • 182
  • 341
  • Why would doing it in init save you from doing it in dealloc, if either is even really necessary? – Dan F Feb 18 '13 at 16:59
  • 4
    Some people like to nil instance fields in `init`, as a kind of "belt and suspenders" thing, and for documentation purposes. It's unnecessary and has nothing to do with what you do later in dealloc. – Hot Licks Feb 18 '13 at 16:59

2 Answers2

8

Neither one is needed.

In the case of the init method, the instance variable will start in nil, so it doesn't matter.

In the case of the dealloc, as your delegate instance variable is (I'm guessing here, but if it's not it should!) set as a weak (ARC) or assign (non-ARC) property, once you dealloc the object nothing will be sent to the delegate.

pgb
  • 24,813
  • 12
  • 83
  • 113
  • 2
    If you're using ARC you should not be using assign for delegate assignment it should be weak. This will automatically clean up the delegate and set it to nil without releasing the address preventing accessing deallocated memory. ARC is rather annoying and nice at the same time. – Holyprin Feb 18 '13 at 19:31
  • Now I'm wondering why Apple code uses `assign` properties for delegate references. – user Feb 10 '14 at 19:30
5

You added this quote:

"This is subtle one but handy one. If you're passing yourself as a delegate to another object, reset that object's delegate before you dealloc."

This is referring to something quite different from the code you posted. The quote applies to the following example:

Foo.m:

- (void)someFooMethod {
    _someBariVar = [[Bar alloc] init];
    _someBariVar.delegate = self;
}

- (void)dealloc { // Foo's dealloc
    _someBariVar.delegate =  nil;
    [_someBariVar release];

    [super dealloc];
}

The point of this is just incase the Bar object is retained by someone else when the Foo dealloc method is called. Since the Foo instance is gone, but the Bar instance isn't, you don't want the Bar instance to still think it has a valid delegate.

rmaddy
  • 314,917
  • 42
  • 532
  • 579