开发者

Let my viewcontroller know when a property changes on class being used as a subview?

I would like a way 开发者_如何学运维for my viewcontroller which has a subview in it, which is it's own class, to find out when a property in this class changes. How do i do this?


KVO - key value observation. See the documentation here

KVO is really neat when you have some central data that can be modified in various places and might have different views that need to refresh when a value updates. It's probably perfect for your requirements. The documentation is comprehensive and has lots of examples.

EXAMPLE:

If we want to know when theClass.propertyName changes, we can add an observer like this;

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

Then you need to implement the following method that will receive the notifications when there is a change.

-(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
    }

}

DO read the documentation though, it explains it all much better.


If you have

@property ... id *yourProperty;

in the .m file, you can implement the

- (void)setYourProperty:(id)yourProperty;

Example:

----

@property (nonatomic, assign) BOOL highligted;

----

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜