![](/img/trans.png)
[英]If add an observer for a notification in the AppDelegate, do I need to bother removing it?
[英]How to add observer to an AppDelegate?
我正在嘗試將觀察者添加到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
}
正如一位評論者所指出的,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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.