2010-11-07 52 views
1

時零USERINFO我張貼這樣的通知,在操作:iPhone發展:收到通知

DownloadStatus * status = [[DownloadStatus alloc] init]; 
    [status setMessage: @"Download started"]; 
    [status setStarted]; 
    [status setCompleteSize: [filesize intValue]]; 
    [userInfo setValue:status forKey:@"state"]; 
    [[NSNotificationCenter defaultCenter] 
     postNotificationName:[targetURL absoluteString] 
     object:nil userInfo:userInfo]; 
    [status release]; 

DownloadStatus是包含安博當前正被下載的下載一些信息的對象。 userInfo是已經在init部分初始化的對象的一個​​屬性,並且保留整個操作持續時間。這是創建這樣:

NSDictionary * userInfo = [NSDictionary dictionaryWithObject:targetURL 
                  forKey:@"state"]; 

「TargetURL中」是一個的NSString,我用這只是爲了確保一切工作正常。當我收到的事件 - 我註冊這樣的:

[[NSNotificationCenter defaultCenter] 
     addObserver:self selector:@selector(downloadStatusUpdate:) 
     name:videoUrl 
     object:nil]; 

這裏的「videoUrl」是包含下載鏈接,這樣我會收到一個網址,我等着看下載的通知的字符串。

的選擇來實現這樣的:

- (void) downloadStatusUpdate:(NSNotification*) note { 

    NSDictionary * ui = note.userInfo; // Tried also [note userInfo] 

    if (ui == nil) { 
     DLog(@"Received an update message without userInfo!"); 
     return; 
    } 
    DownloadStatus * state = [[ui allValues] objectAtIndex:0]; 
    if (state == nil) { 
     DLog(@"Received notification without state!"); 
     return; 
    } 
    DLog(@"Status message: %@", state.message); 
    [state release], state = nil; 
    [ui release], ui = nil; } 

但這種選擇總是收到一個空的用戶信息。我究竟做錯了什麼?

MrWHO

回答

2

這種或那種方式,你似乎是初始化你的用戶信息反對不正確。給定的線:

NSDictionary * userInfo = [NSDictionary dictionaryWithObject:targetURL 
                 forKey:@"state"]; 

會創建一個自動回收的NSDictionary並將其存儲到本地變量。該值不會傳播到您的成員變量。

假設這是一個片段,然後是例如

self.userInfo = userInfo; 

分配的本地成員,同時保留它,那麼你的代碼應該在這一行產生異常:

[userInfo setValue:status forKey:@"state"]; 

因爲它試圖變異不可變對象。因此,更有可能的是userInfo的值沒有被存儲,並且你在那個時候沒有消息傳遞。

所以,我認爲 - 假設你有USERINFO聲明爲 '保留' type屬性,要替換:

NSDictionary * userInfo = [NSDictionary dictionaryWithObject:targetURL 
                 forKey:@"state"]; 

有了:

self.userInfo = [NSMutableDictionary dictionaryWithObject:targetURL 
                 forKey:@"state"]; 
+0

謝謝你!就是這樣 - 現在看起來很明顯,當我看着代碼時我看不到它。感謝您的幫助! – MrWHO 2010-11-07 23:48:55