开发者

NSoperation and key value observing

I am creating a MyOperation object (inherited from NSOperation) and add to a NSOperationQueue. Then I am doing KVO on MyOperation. I am using this method

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context;

to get a value from MyOperation if开发者_运维百科 it is finished. In this method I am using a convenience method from an other class to get some other data.

Maybe here synchronization problems in the observeValue... method?


NSOperation uses KVO intrinsically in it's operation; having to implement isFinished and isExecuted as part of the processing, for example are 100% KVO and are part of an operation's required contract with a client/queue. So advising that these should be avoided is inaccurate; NSOperation uses KVO itself so adopting dannywartnaby's premise would indicate that the implementation of NSOperation is in itself flawed, which is definitely not the case.

Admittedly the developer must take care to use KVO properly, although i would argue that subclassing NSOperation is a non-trivial task probably left for the more experienced Objective-C programmer. Notifications, one could argue, are too coarse grained for the kind of work undertaken by an operation, although not always, i think we must be careful when advising on practices to ensure that the wrong message isnt passed as best practice. Danny, would you care to elaborate on why using KVO is not advised when using NSOperation or threads? many examples of NSOperation implementation use KVO...


I don't know your use-case, but using KVO for threads/operations isn't wise.

You could instead have your Operation object post a notification once it's complete. Or alternatively define a delegate protocol and give your Operation a delegate... you can then define some kind of 'myOperationComplete:' method which is invoked by your Operation against the delegate it was given, using performSelectorOnMainThread.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜