0

I read a tip here in a SO best practices posting:

"If you're passing yourself as a delegate to another object, reset that object's delegate before you dealloc." EXAMPLE:

- (void)dealloc {
    if (self.someObject.delegate == self) {
        self.someObject.delegate = NULL;
    }
    self.someObject = NULL;
    [super dealloc];
}

Sounds reasonable, but I'm not sure in what cases I need to do that. For example, I have a view controller like the one below:

- (void) viewDidLoad {
    myTextField.returnKeyType = UIReturnKeyDone;
    myTextField.delegate = self;
}

Would I (Should I) set the delegate to NULL in that case, for example:

- (void) dealloc {

    if (self.myTextField.delegate == self) {
        self.myTextField.delegate = NULL;
    }
    [myTextField release];
    [super dealloc];
}
Community
  • 1
  • 1
Lauren Quantrell
  • 2,647
  • 6
  • 36
  • 49
  • 3
    It is worth noting that you should probably be using nil rather than NULL. [This SO question](http://stackoverflow.com/questions/557582/null-vs-nil-in-objective-c) has some discussion on the matter – Simon Goldeen May 18 '11 at 21:59

1 Answers1

0

If the object doing the delegating could be getting retained somewhere else and you don't set the delegate to nil there's a chance that your object could be called after it's dealloc, which would manifest as a crash. In this specific case you'd probably be okay, but it certainly won't hurt anything to do this.

Collin
  • 478
  • 5
  • 7