让我的viewcontroller知道属性何时在用作子视图的类上更改?

时间:2011-05-26 17:24:36

标签: iphone objective-c

我想为我的viewcontroller提供一种方法,它有一个子视图,这是它自己的类,可以找出这个类中的属性何时发生变化。我该怎么做?

2 个答案:

答案 0 :(得分:5)

KVO--关键值观察。 See the documentation here

当你有一些可以在不同地方修改的中央数据时,KVO真的很整洁,并且可能有不同的视图需要在值更新时刷新。它可能完全符合您的要求。文档很全面,有很多例子。

实施例

如果我们想知道theClass.propertyName何时更改,我们可以添加这样的观察者;

[theClass addObserver:self forKeyPath:@"propertyName" options:0 context:nil];   

然后,您需要实现以下方法,以便在发生更改时收到通知。

-(void) observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{   

    if ([keyPath isEqualToString: @"propertyName"]) {
         // Do stuff that you want to do when theClass.propertyName has changed
    }

}

请仔细阅读文档,它解释得更好。

答案 1 :(得分:0)

如果你有

@property ... id *yourProperty;

.m 文件中,您可以实现

- (void)setYourProperty:(id)yourProperty;

示例:

----

@property (nonatomic, assign) BOOL highligted;

----

- (void)setHighlighted:(BOOL)highlighted {
    // execute some code
}