What does it mean? Let’s look at the view hierarchy

1
2
3
JSView
|---- titleLabel
|---- ...

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
2
3
4
- (void)dealloc
{
[self removeObserver:self forKeyPath:@"_titleLabel.text"];
}

Don’t forget to remove it after the main view deallocated, otherwise the app will crash.

1
2
3
4
5
6
7
8
#pragma mark - observer
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([keyPath isEqualToString:@"_titleLabel.text"])
{
NSLog(@"the title text has been changed");
}
}

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
2
3
4
- (void)dealloc
{
[_titleLabel removeObserver:self forKeyPath:@"text"];
}
1
2
3
4
5
6
7
8
9
#pragma mark - observer
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (object == _titleLabel) {
if ([keyPath isEqualToString:@"text"]) {
NSLog(@"the title text has been changed");
}
}
}

References: