Reputation: 85
I'm trying to observe a property variable (xxx
) of ResultDataClass
. In my working ViewController
, I wrote the following.
-(void)dealloc {
ResultDataClass *resultData = [ResultDataClass getInstance];
[resultData addObserver:self forKeyPath:@"xxx" options:NSKeyValueObservingOptionNew context:NULL];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
self.solutionText.text = @"test1";
if([keyPath isEqualToString:@"xxx"]) {
self.solutionText.text = @"test2";
}
}
solutionText
is a UITextView
in my working ViewController
.
After running the program, nothing was shown in the textview.
Anyone know how to fix this?
Thank you and sorry for my English.
Upvotes: 1
Views: 1030
Reputation: 107231
You written the observer in dealloc
method. There will be an issue, your object is being released when you are adding an observer, so there will be a crash when the KVO value is changed.
There is no crash and nothing is working, I think the reason is; the dealloc
method is never called. It means your view controller is never released (potentially a leak, a strong retain cycle is there).
Instead of that add that in your viewDidLoad:
- (void)viewDidLoad
{
[super viewDidLoad];
ResultDataClass *resultData = [ResultDataClass getInstance];
[resultData addObserver:self forKeyPath:@"xxx" options:NSKeyValueObservingOptionNew context:NULL];
}
Upvotes: 1