问题
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?
回答1:
I havent enough reputation to comment or down-vote but i would down-vote dannywartnaby's answer. 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...
回答2:
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.
来源:https://stackoverflow.com/questions/2608355/nsoperation-and-key-value-observing