我有一个解析器类和一些视图控制器类。在解析器类中,我发送了一个请求并接收了一个异步响应。我想要多个下载,比如每个视图控制器一个。因此,我在每个类中都注册了一个观察者:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataDownloadComplete:) name:OP_DataComplete object:nil];然后在以下位置发布通知:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection method of the parser class.
[[NSNotificationCenter defaultCenter] postNotificationName:OP_DataComplete object:nil];但是,在运行代码时,第一个视图控制器运行良好,但是对于第二个视图控制器,在下载和解析器类发布通知之后,代码进入第一个类的dataDownloadComplete: method,尽管我每次都在选择器中指定了不同的方法名。我不明白错误可能是什么。请帮帮忙。提前谢谢。
发布于 2011-04-08 16:56:11
两个视图控制器都在侦听通知,因此两个方法都应该一个接一个地被调用。
有几种方法可以解决这个问题。对于通知来说,最简单的方法是包含某种标识符,视图控制器可以查看它是否应该忽略它。NSNotifications对此有一个userInfo属性。
NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:@"viewController1", @"id", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:OP_DataComplete object:self userInfo:info];当你收到通知时,检查一下它是给谁的:
- (void)dataDownloadComplete:(NSNotification *)notification {
NSString *id = [[notification userInfo] objectForKey:@"id"];
if (NO == [id isEqualToString:@"viewController1"]) return;
// Deal with the notification here
...
}还有一些其他的方法来处理它,但是如果不了解你的代码,我就不能很好地解释它们--基本上你可以指定你想要侦听通知的对象(参见how I have object:self but you sent object:nil),但有时你的架构不允许这种情况发生。
发布于 2011-04-08 17:10:57
最好是创建一个协议:
@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];还有一些事情需要实现--它只是一个表单。它更安全,涉及到直接消息传递、裁判计数、取消等等。
https://stackoverflow.com/questions/5592359
复制相似问题