2011-04-08 25 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]; 

存在實現一些事情 - 它只是一個形式。它更安全,涉及直接消息傳遞,參考計數,取消等。