Custom setter methods in Core-Data

前端 未结 5 1106
夕颜
夕颜 2020-12-07 18:09

I need to write a custom setter method for a field (we\'ll call it foo) in my subclass of NSManagedObject. foo is defined in the data

5条回答
  •  天命终不由人
    2020-12-07 18:57

    Here's how I'm doing KVO on the id attribute of a Photo : NSManagedObject. If the photo's ID changes, then download the new photo.

    #pragma mark NSManagedObject
    
    - (void)awakeFromInsert {
        [self observePhotoId];
    }
    
    - (void)awakeFromFetch {
        [self observePhotoId];
    }
    
    - (void)observePhotoId {
        [self addObserver:self forKeyPath:@"id"
                  options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:NULL];
    }
    
    - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change
                           context:(void *)context {
        if ([keyPath isEqualToString:@"id"]) {
            NSString *oldValue = [change objectForKey:NSKeyValueChangeOldKey];
            NSString *newValue = [change objectForKey:NSKeyValueChangeNewKey];        
            if (![newValue isEqualToString:oldValue]) {
                [self handleIdChange];
            }
        }
    }
    
    - (void)willTurnIntoFault {
        [self removeObserver:self forKeyPath:@"id"];
    }
    
    #pragma mark Photo
    
    - (void)handleIdChange {
        // Implemented by subclasses, but defined here to hide warnings.
        // [self download]; // example implementation
    }
    

提交回复
热议问题