iPhone Key-Value Observer: observer not registering in UITableViewController

Posted by Scott on Stack Overflow See other posts from Stack Overflow or by Scott
Published on 2009-10-17T16:36:17Z Indexed on 2010/03/13 10:05 UTC
Read the original article Hit count: 558

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"];

© Stack Overflow or respective owner

Related posts about objective-c

Related posts about iphone