iPhone Key-Value Observer: observer not registering in UITableViewController
- by Scott
Hi Fellow iPhone Developers,
I am an experienced software engineer but new to the iPhone platform. I have successfully implemented sub-classed view controllers and can push and pop parent/child views on the view controller stack. However, I have struck trouble while trying to update a view controller when an object is edited in a child view controller. After much failed experimentation, I discovered the key-value observer API which looked like the perfect way to do this. I then registered an observer in my main/parent view controller, and in the observer I intend to reload the view. The idea is that when the object is edited in the child view controller, this will be fired. However, I think that the observer is not being registered, because I know that the value is being updated in the editing view controller (I can see it in the debugger), but the observing method is never being called.
Please help!
Code snippets follow below.
Object being observed. I believe that this is key-value compliant as the value is set when called with the setvalue message (see Child View Controller below).
X.h:
@interface X : NSObject <NSCoding> {
NSString *name;
...
@property (nonatomic, retain) NSString *name;
X.m:
@implementation X
@synthesize name;
...
Main View Controller.h:
@class X;
@interface XViewController : UITableViewController {
X *x;
...
Main View Controller.m:
@implementation XViewController
@synthesize x;
...
- (void)viewDidLoad {
...
[self.x addObserver:self
forKeyPath: @"name"
options: (NSKeyValueObservingOptionNew |
NSKeyValueObservingOptionOld)
context:nil];
[super viewDidLoad];
}
...
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqual:@"name"]) {
NSLog(@"Found change to X");
[self.tableView reloadData];
}
[super observeValueForKeyPath:keyPath
ofObject:object
change:change
context:context];
}
Child View Controller.m: (this correctly sets the value in the object in the child view controller)
[self.x setValue:[[tempValues objectForKey:key] text] forKey:@"name"];