未能实现 KVO 来跟踪 BOOL 属性

问题描述 投票:0回答:1

我已经成功为我的 keyPath @"isFinished" 实现了 KVO,但我无法对其他属性执行相同的操作:isOfflineContentNil; 它的更改未注册。

对象:

@property (nonatomic) BOOL isFinished;
@property (nonatomic) BOOL isOfflineContentNil;

@end

@implementation DataManager

-(instancetype)init {
  
  self = [super init];
  
  if (self) {
    [[NSUserDefaults standardUserDefaults] setObject:@[@{@"website" : @"TechCrunch", @"title" : @"New iPhone comming", @"authors" : @"some", @"date" : @"06/08/2014"},@{@"website" : @"TheVerge", @"title" : @"Macbook line refreshed", @"authors" : @"john", @"date" : @"16/09/2014"}] forKey:@"savedNews"];
    self.isOfflineContentNil = YES;
    
    NSMutableArray *userDefault = [[NSUserDefaults standardUserDefaults] objectForKey:@"savedNews"];
    
    if (userDefault) {
      self.savedForLaterNews = userDefault;
      self.isOfflineContentNil = NO;
    }
    
    dispatch_async(kBgQueue, ^{
      NSData *data = [NSData dataWithContentsOfURL:kLatestNewsURL];
      [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];
    });

    self.isFinished = NO;
  }
  
  return self;
}

-(void)fetchedData:(NSData *)responseData {
  
  NSError *error;
  
  self.json = [NSJSONSerialization JSONObjectWithData:responseData
                                              options:kNilOptions
                                                error:&error];
  self.currentNews = [self.json mutableCopy];
  self.isFinished = YES;
  [self sortJSONInformation];

}

听众:

self.dataManager = [DataManager new];
  [self.dataManager addObserver:self forKeyPath:@"isFinished" options:NSKeyValueObservingOptionOld context:nil];
  [self.dataManager addObserver:self forKeyPath:@"isOfflineContentNil" options:NSKeyValueObservingOptionOld context:nil];
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
                       change:(NSDictionary *)change context:(void *)context {

  if ([keyPath isEqualToString:@"isFinished"]) {

    [self animateViewDismiss:self.loadingView];
  } else if ([keyPath isEqualToString:@"isOfflineContentNil"]) {

    self.isCurrentNews = NO;
    [self animateViewDismiss:self.loadingView];
  } else {
    [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  }
}
objective-c key-value-observing
1个回答
4
投票

发现我需要将观察选项修改为

options:NSKeyValueObservingOptionInitial

相当罕见,但适用于这种情况。

© www.soinside.com 2019 - 2024. All rights reserved.