2013-05-31 151 views
0

我想添加一个观察者的AppDelgate属性,但它不工作的原因,所以只是想知道如果我失去了一些东西。如何将观察者添加到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

'dataDict' KVO-compliant? – Tommy

+1

定义“不工作”。你的意思是说你的'observeValueForKeyPath ...'方法在你认为应该的时候从来没有被调用过? dataDict是你的应用程序委托的属性吗?显示你如何定义它。你有自己的“setter”方法还是综合?如果你自己的,发布你的setter方法。 – rmaddy

+0

它是一个AppDelegate属性,所以它是kVO的投诉。 – Ashutosh

回答

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