iphone - 添加 bool 值的观察者

标签 iphone objective-c ios observer-pattern

我正在尝试向对象添加观察者并通过更改它的 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/

相关文章:

iphone - iOS 使用 AVFoundation 组合视频

iphone - 使用 NSMutableArray 与 NSArray 的缺点?

iphone - AppStore会拒绝登录类型的应用程序吗?

ios - 如何在 iOS 中对大小字符串的 NSArray 进行排序?

ios - 使用 Spotify IOS SDK 获取每首轨道的封面艺术?

iphone - 在 iPhone 上以编程方式接听来电

ios - 谷歌将不再允许在嵌入式浏览器中向谷歌发出 OAuth 请求

ios - 如何确定具有角度的最近 CGPoint 和另一个 CGPoint

ios - NSDateFormatter 是否正确格式化了我的时区?

ios - UINavigationitem 自定义 rightBarButtonItems