对象是否可以订阅自己的通知?

时间:2011-11-03 17:41:06

标签: objective-c design-patterns uitextfield nsnotifications uitextfielddelegate

例如,a UITextField cannot be its own delegate,但它可以让自己注册为自己的通知观察者吗?看起来很奇怪,但似乎工作正常。想法?

// 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

1 个答案:

答案 0 :(得分:1)

你正在做的事似乎很好,但对于这个特定的例子有一个更纯粹的解决方案:

// 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

查看UIControlEvents reference