如何将观察者添加到AppDelegate?

时间:2013-05-31 22:04:04

标签: ios objective-c key-value-observing

我正在尝试将观察者添加到AppDelegate的属性中,但由于某些原因它无法正常工作,所以我只想知道我是否遗漏了某些内容。

这是我正在使用的代码:

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

}

1 个答案:

答案 0 :(得分:0)

正如一位评论者指出的那样,AppDelegate不是UIViewController,因此实施-viewDidLoad不太可能取得成果。如果您正在寻找“启动”方法,那么在这种特殊情况下您可能需要-awakeFromNib。像这样:

@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
相关问题