Why does NSOperation disable automatic key-value observing?

前端 未结 4 854
臣服心动
臣服心动 2020-12-13 07:14

When working with a custom NSOperation subclass I noticed that the automatic key-value observing is disabled by the [NSOperation automaticallyNotifiesObse

4条回答
  •  萌比男神i
    2020-12-13 07:49

    While I agree that overriding automaticallyNotifiesObserversForKey appears to work, but I personally forgo the isExecuting and isFinished properties altogether and instead define executing and finished properties, which, as Kevin suggests, is more consistent with modern conventions:

    @property (nonatomic, readwrite, getter = isExecuting) BOOL executing;
    @property (nonatomic, readwrite, getter = isFinished)  BOOL finished;
    

    I then write custom setters for these two properties, which do the necessary isExecuting and isFinished notifications:

    - (void)setExecuting:(BOOL)executing
    {
        [self willChangeValueForKey:@"isExecuting"];
        _executing = executing;
        [self didChangeValueForKey:@"isExecuting"];
    }
    
    - (void)setFinished:(BOOL)finished
    {
        [self willChangeValueForKey:@"isFinished"];
        _finished = finished;
        [self didChangeValueForKey:@"isFinished"];
    }
    

    This yields:

    • a more customary BOOL property declaration;
    • custom setters satisfy the strange notifications that NSOperation requires; and
    • I can now just use the executing and finished setters throughout my operation implementation, without littering my code with notifications.

    I must confess that I like the elegance of overriding automaticallyNotifiesObserversForKey, but I just worry about unintended consequences.


    Note, if doing this in iOS 8 or Yosemite, you will also have to explicitly synthesize these properties in your @implementation:

    @synthesize finished  = _finished;
    @synthesize executing = _executing;
    

提交回复
热议问题