最好创建一个协议:
@protocol MONStuffParserRecipientProtocol
@required
- (void)parsedStuffIsReady:(NSDictionary *)parsedStuff;
@end
并声明视图控制器:
@class MONStuffDownloadAndParserOperation;
@interface MONViewController : UIViewController < MONStuffParserRecipientProtocol >
{
MONStuffDownloadAndParserOperation * operation; // add property
}
...
- (void)parsedStuffIsReady:(NSDictionary *)parsedStuff; // implement protocol
@end
并添加一些后端:到视图控制器
- (void)displayDataAtURL:(NSURL *)url
{
MONStuffDownloadAndParserOperation * op = self.operation;
if (op) {
[op cancel];
}
[self putUpLoadingIndicator];
MONStuffDownloadAndParserOperation * next = [[MONStuffDownloadAndParserOperation alloc] initWithURL:url recipient:viewController];
self.operation = next;
[next release], next = 0;
}
并使操作保持在视图控制器上:
@interface MONStuffDownloadAndParserOperation : NSOperation
{
NSObject<MONStuffParserRecipientProtocol>* recipient; // << retained
}
- (id)initWithURL:(NSURL *)url Recipient:(NSObject<MONStuffParserRecipientProtocol>*)recipient;
@end
并在下载和解析数据时将操作消息发送给收件人:
// you may want to message from the main thread, if there are ui updates
[recipient parsedStuffIsReady:parsedStuff];
还有更多的东西要实现——它只是一种形式。它更安全,涉及直接消息传递、引用计数、取消等。