2011-04-08 34 views
0

我有一个解析器类和一些视图控制器类。在解析器类中,我发送请求并接收异步响应。我想要多次下载,每个viewcontroller一个。所以,我在每个类注册一个观察者:多次下载的NSnotifications

[[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:方法,尽管我每次都在选择器中指定了不同的方法名称。我不明白错误可能是什么。请帮忙。提前致谢。

+0

请提供一些代码。 – 2011-04-08 08:23:08

回答

1

两个视图控制器正在侦听通知,所以这两个方法应该被一个接一个地调用。

有几种方法可以解决这个问题。最简单的方法是通知包含某种标识符,视图控制器可以查看它是否应该忽略它。 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 
    ... 
} 

还有一些其他的方法来处理它,但不知道更多关于你的代码,我无法解释他们很好 - 基本上你可以指定你想要收听通知的对象(看看我有没有object:self,但是你发送object:nil),但有时候你的架构不允许这样做。

+0

嗨,Dean,谢谢,这很容易,我现在正在使用字典并传递它的objectForKey。有用 。 – 2011-04-08 15:26:05

0

最好是创建一个协议:

@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]; 

存在实现一些事情 - 它只是一个形式。它更安全,涉及直接消息传递,参考计数,取消等。