-1

I want to make Observing for NSString of Custom class.

//add

[self.sourceUser addObserver:[self appDelegate] forKeyPath:@"uJid" options:0 context:nil];

//remove

[self.sourceUser removeObserver:[self appDelegate] forKeyPath:@"uJid" context:nil];

In app Delegate I use

- (void)didChangeValueForKey:(NSString *)key
{
    if ([key isEqualToString:@"uJid"])
    {
       //     self.iHopeItTemp = object       
    }
}

But I not get it, Why? How Can I get new parameter of my object?

Jamie Taylor
  • 4,709
  • 5
  • 44
  • 66

1 Answers1

1

Instead of didChangeValueForKey you need to use observeValueForKeyPath. Check the documentation for an example.

- (void)observeValueForKeyPath:(NSString *)keyPath
                      ofObject:(id)object
                        change:(NSDictionary *)change
                       context:(void *)context {

    if ([keyPath isEqual:@"uJid"]) {
        // your code
    }
    /*
     Be sure to call the superclass's implementation *if it implements it*.
     NSObject does not implement the method.
     */
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
Merlevede
  • 8,140
  • 1
  • 24
  • 39
  • 1
    If it's not working, then you need to actually generate some KVO notifications for the property change. Invoke `-[NSObject willChangeValueForKey:]` and `-[NSObject didChangeValueForKey:]` and see if that does the trick. – CodaFi Mar 23 '14 at 04:24
  • @Merlevede, I create [self addObserver:self forKeyPath:@"messageVC.user.uJid" options:0 context:nil]; in mapVC for property messageVC but then I adn I get observeValueForKeyPath. Then I move observeValueForKeyPath to appDelegate I not get it with [self addObserver:[self appDelegate] forKeyPath:@"messageVC.user.uJid" options:0 context:nil]; in mapVC – user3443009 Mar 23 '14 at 17:46
  • The error is in the first `self`, you're not adding an observer to self, but on your mapVC, so you should replace `self` with your `mapVC` instance. – Merlevede Mar 23 '14 at 17:57