objective-ckey-value-observing

Fail to implement KVO to track BOOL property


I've successfully implemented the KVO for my keyPath @"isFinished", but I'm not being able to do the same with the other property: isOfflineContentNil; Its changes aren't registered.

Object:

@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];

}

Listener:

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];
  }
}

Solution

  • Found out that I needed to modify the observing option to

    options:NSKeyValueObservingOptionInitial
    

    pretty uncommon, but applies to the situation.