我正在尝试向对象添加观察者并通过更改它的 bool 值来触发它。
代码: 添加观察者:
[unitsCellViewController.cell addObserver:self forKeyPath:@"unit" options:0 context:nil];
在对象中,当文本字段发生变化时,我将更改 bool 值并尝试触发通知:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
if ([string length] != 0)
{
NSRange match = [@"0123456789" rangeOfString:string];
if (match.location == NSNotFound) {
return NO;
}
}
[self willChangeValueForKey:@"unit"];
self.on = !on;
[self didChangeValueForKey:@"unit"];
return YES;
}
但这不起作用,值确实发生了变化,但观察者没有被触发。 我这样做正确吗?如果没有,如何在文本字段更改时触发事件?
最佳答案
您可以使用属性,并覆盖 setter
在你的.h中
@property (nonatomic, assign) BOOL myFlag;
在你的.m
@implementation
@synthesize myFlag = _myFlag;
...
..
.
- (void)setMyFlag:(BOOL)myFlag
{
if(myFlag != _myFlag){
_myFlag = myFlag;
[self postNotification];
}
}
-(void)postNofitication
{
[[NSNotificationCenter defaultCenter] postNotificationName:@"nameOfNotification" object:nil];
}
当标志的值发生变化时,您执行一个操作。
希望这能有所帮助。
关于iphone - 添加 bool 值的观察者,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7810442/