0

我正在尝试将观察者添加到 AppDelgate 的属性中,但由于某种原因它不起作用,所以只是想知道我是否遗漏了一些东西。

这是我正在使用的代码:

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

}
4

1 回答 1

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
于 2013-06-17T13:48:35.963 回答