iOS - event listener to property of property
What does it mean? Let’s look at the view hierarchy
1 | JSView |
In this case, I have a viewController that contain a property UILabel titleLabel
. I want to perform some action upon the text
changed.
i.e.
1 | jsView.titleLabel.text = @"new text"; |
Now, add an event listener (in iOS called observer) to it’s text changed
1 | [self addObserver:self forKeyPath:@"_titleLabel.text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; |
you can add the line above to init
method
1 | - (void)dealloc |
Don’t forget to remove it after the main view deallocated, otherwise the app will crash.
1 |
|
Once the text changed, it will output the console
Update Jan 6, 2015
The more proper way would be
1 | [_titleLabel addObserver:self forKeyPath:@"text" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil]; |
1 | - (void)dealloc |
1 |
|
References: