0

I am trying to add an observer to a property of AppDelgate but its not working for some reason, so just wanted to know if i am missing something.

Here's the code i am using:

AppDelegate.h

@property(strong, nonatomic) NSDictionary * dataDict;

AppDelegate.m

-(void)viewDidLoad{
[(AppDelegate *)[[UIApplication sharedApplication] delegate] addObserver:self forKeyPath:@"dataDict" options:0 context:nil];
}

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

}
Ashutosh
  • 5,614
  • 13
  • 52
  • 84
  • 1
    Is `dataDict` KVO-compliant? – Tommy May 31 '13 at 22:38
  • 1
    Define "not working". Do you mean that your `observeValueForKeyPath...` method is never called when you think it should? Is `dataDict` a property of your app delegate? Show how you define it. Do you have your own "setter" method or is it synthesize? If your own, post your setter method. – rmaddy May 31 '13 at 22:41
  • Its a AppDelegate property, so it is kVO complaint. – Ashutosh Jun 01 '13 at 03:42
  • Why is there a `viewDidLoad` in `AppDelegate`? Are you sure `addObserver:` is called? – maroux Jun 01 '13 at 06:22

1 Answers1

0

As one commenter pointed out, an AppDelegate isn't a UIViewController, so implementing -viewDidLoad isn't likely to bear fruit. You probably want -awakeFromNib in this particular case if you're looking for a "startup" method. Something like this:

@interface AppDelegate : NSObject <UIApplicationDelegate>
@property (strong, nonatomic) NSDictionary * dataDict;
@end

@implementation AppDelegate

static void * const MyDataDictObservation = (void*)&MyDataDictObservation;

- (void)awakeFromNib
{
    [self addObserver: self forKeyPath:@"dataDict" options:0 context:MyDataDictObservation];
    // ... other stuff ...
}

- (void)dealloc
{
    [self removeObserver: self forKeyPath:@"dataDict" context:MyDataDictObservation];
    // ... other stuff ...
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (MyDataDictObservation == context)
    {
        // Do something
    }
    else
    {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
@end
ipmcc
  • 29,581
  • 5
  • 84
  • 147