无法实现KVO来跟踪BOOL属性

时间:2014-08-29 05:10:27

标签: objective-c key-value-observing

我已成功为我的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];
  }
}

Lorem ipsum dolor sit amet,consectetuer adipiscing elit,sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat。 Ut wisi enim ad minim veniam,quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat。 Duis autem vel eum iriure

1 个答案:

答案 0 :(得分:4)

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

options:NSKeyValueObservingOptionInitial

非常罕见,但适用于这种情况。

相关问题