1

For example, a UITextField cannot be its own delegate, but is it OK to just have it register itself as an observer of its own notifications? Looks weird but seems to work fine. Thoughts?

// MyTextField.h

@interface MyTextField : UITextField
@end

// MyTextField.m

@interface MyTextField ()
- (void)myTextFieldDidChange:(NSNotification *)notification;
@end

@implementation MyTextField

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [[NSNotificationCenter defaultCenter]
         addObserver:self
         selector:@selector(myTextFieldDidChange:)
         name:UITextFieldTextDidChangeNotification
         object:self];
    }
}

- (void)myTextFieldDidChange:(NSNotification *)notification {
    // Do custom stuff here.
}

@end
ma11hew28
  • 121,420
  • 116
  • 450
  • 651
  • 1
    You are turning a view into a controller, but if it works it works. For better MVC, have the ViewController that contains the textfield be the delegate. – Jesse Black Nov 03 '11 at 17:55
  • But, the method above keeps the view controller cleaner and allows the `MyTextField` to be reused in other view controllers without them having to re-implement the `textFieldDidChange:` functionality in exactly the same way. – ma11hew28 Nov 03 '11 at 19:37

1 Answers1

1

What you're doing seems fine, but there's a purer solution for this particular example:

// MyTextField.h

@interface MyTextField : UITextField
@end

// MyTextField.m

@interface MyTextField ()
- (void)myTextFieldDidChange:(UITextField *)textField;
@end

@implementation MyTextField

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self addTarget:self action:@selector(myTextFieldDidChange:)
       forControlEvents:UIControlEventEditingChanged];
    }
    return self;
}

- (void)myTextFieldDidChange:(MyTextField *)myTextField {
    // Do custom stuff here.
}

@end

Check out the UIControlEvents reference.

ma11hew28
  • 121,420
  • 116
  • 450
  • 651