Shubham bairagi Shubham bairagi - 4 years ago 140
Swift Question

Set observer to object change

I am searching for a way where i am can create a method, which called only when any changes applies on Object

For Example let's take a label. i am changing text of this label in different cases. Now what i need i created one method:

- (void)labelTextChangeNotification {

}


It will call every time when my label text will change
i can use NSNotification for getting this. for
NSNotification
we need to Post Notification.
My requirement is like Observer which observe my label text change.
is there any way to get this ??

Answer Source

You can try using key-value observing (KVO):

[label addObserver:self
    forKeyPath:@"text"
       options:NSKeyValueObservingOptionNew
             | NSKeyValueObservingOptionOld
       context:NULL];

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"text"]) {
    /* etc. */
}
}

When you change value of label this observervalue method will be called. Also in the change Dictionary you will find all the detail.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download