Iphone 多次下载的通知

Iphone 多次下载的通知,iphone,objective-c,nsnotifications,Iphone,Objective C,Nsnotifications,我有一个解析器类和一些视图控制器类。在解析器类中,我发送一个请求并接收一个异步响应。我想要多个下载,比如说每个viewcontroller一个。因此,我在每个类中注册了一个观察者: [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dataDownloadComplete:) name:OP_DataComplete object:nil]; 然后在以下位置发布通知: -(void)connec

我有一个解析器类和一些视图控制器类。在解析器类中,我发送一个请求并接收一个异步响应。我想要多个下载,比如说每个viewcontroller一个。因此,我在每个类中注册了一个观察者:

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

但是在运行代码时,第一个viewcontroller工作正常,但对于下载后的第二个viewcontroller,解析器类无限地发布通知,代码进入第一个类的datadownloadplete:method,尽管每次我都在选择器中指定了不同的方法名称。我不明白可能是什么错误。请帮忙。提前感谢。

两个视图控制器都在侦听通知,因此应该一个接一个地调用这两个方法

有几种方法可以解决这个问题。最简单的方法是通知包含某种标识符,视图控制器可以查看该标识符,以确定是否应该忽略它。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
)但有时您的体系结构不允许这种情况发生。

最好创建一个协议:

@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
@interface MONStuffDownloadAndParserOperation : NSOperation
{
  NSObject<MONStuffParserRecipientProtocol>* recipient; // << retained
}

- (id)initWithURL:(NSURL *)url Recipient:(NSObject<MONStuffParserRecipientProtocol>*)recipient;

@end
并使操作保持在视图控制器上:

@class MONStuffDownloadAndParserOperation;

@interface MONViewController : UIViewController < MONStuffParserRecipientProtocol >
{
  MONStuffDownloadAndParserOperation * operation; // add property
}
...
- (void)parsedStuffIsReady:(NSDictionary *)parsedStuff; // implement protocol

@end
@interface MONStuffDownloadAndParserOperation : NSOperation
{
  NSObject<MONStuffParserRecipientProtocol>* recipient; // << retained
}

- (id)initWithURL:(NSURL *)url Recipient:(NSObject<MONStuffParserRecipientProtocol>*)recipient;

@end

还有一些东西需要实现——它只是一种形式。它更安全,包括直接发送消息、引用计数、取消等。

嗨,迪安,谢谢,这更容易,我现在正在使用字典并将其传递给objectForKey。它起作用了。