添加布尔值的观察者
我正在尝试向对象添加观察者并通过更改它的布尔值来触发它。
代码: 添加观察者:
[unitsCellViewController.cell addObserver:self forKeyPath:@"unit" options:0 context:nil];
在对象中,当文本字段发生变化时,我将更改布尔值并尝试触发通知:
- (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;
}
但这不起作用,值确实发生了变化,但观察者没有被触发。 我这样做正确吗?如果没有,如何在文本字段更改时触发事件?
I am trying to add an observer to an object and trigger it by changing it boolean value.
Code:
Add Observer:
[unitsCellViewController.cell addObserver:self forKeyPath:@"unit" options:0 context:nil];
In the object, when the textfield is changing, I will change the boolean value and try to trigger the notification:
- (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;
}
but this is not working, the value did get changed, but the observer is not triggered.
Am I doing this correctly? If not, how can I trigger the event when the textfield is changed?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用属性,并覆盖 setter
在 .h 中
在 .m 中
并且当标志的值发生变化时执行操作。
希望这能有所帮助。
You can use a property, and override the setter
In your .h
In your .m
And you perform an action just when the value of the flag change.
Hope this can help.