1

在我的iOS應用程序中,我發佈NSNotification並在主線程中將其捕獲到我的UIView之一中。我想傳遞額外的信息和通知。我使用userInfo字典NSNotificationNSNotificationCenter postNotification方法中的對象參數

[[NSNotificationCenter defaultCenter] postNotificationName:@"NotifyValueComputedFromJS" object:self userInfo:@{@"notificationKey":key,@"notificationValue":value,@"notificationColor":color,@"notificationTimeStamp":time}]; 

key,value,color和time是包含我需要傳遞的值的局部變量。在UIView我加入觀察員該通知,我使用notification.userInfo得到這些數據

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"NotifyValueComputedFromJS" object:nil]; 

-(void)receiveNotification:(NSNotification *)notification 
{ 
    if ([notification.userInfo valueForKey:@"notificationKey"]!=nil && [[notification.userInfo valueForKey:@"notificationKey"] isEqualToString:self.notificationKey] && [notification.userInfo valueForKey:@"notificationValue"]!=nil) { 
     [self updateLabelWithValue:[notification.userInfo valueForKey:@"notificationValue"]]; 
    } 
} 

在此通知發佈的4倍在一秒鐘的頻率。我在主線程中也做了一些動畫。我在這裏面臨的問題是我的用戶界面滯後。用戶界面會對滾動事件做出響應,或者觸摸事件的時間很長(我已經面對延遲1到2秒)。經過一番研究後,我才知道NSDictionary體積龐大,如果在主線程中使用會造成延遲。有沒有其他方法可以通過NSNotification傳遞我的數據?

我試過了另一種方式。我創建了一個自定義NSObject類來保存我想要的數據,並將其作爲postNotification方法的對象參數傳遞給它。

[[NSNotificationCenter defaultCenter] postNotificationName:@"NotifyValueComputedFromJS" object:customDataObject userInfo:nil]; 

這裏customDataObject是我的自定義NSObject類的一個實例。我知道這個參數是通知的發送者(通常它會是自己的)。如果我將自定義對象作爲參數發送,這是錯誤的方法嗎?

回答

2

正如BobDave提到的,關鍵是在主UI線程以外的某個線程上發送通知。這可以通過dispatch_async或隊列完成。

此行爲的典型模式是發件人:

-(void)sendDataToObserver { 
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ 
     [[NSNotificationCenter defaultCenter] postNotificationName:@"NotifyValueComputedFromJS" object:customDataObject userInfo:userInfo:@{@"notificationKey":key,@"notificationValue":value,@"notificationColor":color,@"notificationTimeStamp":time}]; 
    }); 
} 

和接收器(注:弱自我,因爲保留週期):

-(void)addObserver { 
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveNotification:) name:@"NotifyValueComputedFromJS" object:nil]; 
} 

-(void)receiveNotification:(NSNotification *)notification { 
    if ([notification.userInfo valueForKey:@"notificationKey"]!=nil && [[notification.userInfo valueForKey:@"notificationKey"] isEqualToString:self.notificationKey] && [notification.userInfo valueForKey:@"notificationValue"]!=nil) { 
     __weak typeof (self) weakSelf = self; 

     dispatch_async(dispatch_get_main_queue(), ^{ 
      [weakSelf updateLabelWithValue:[notification.userInfo valueForKey:@"notificationValue"]]; 
     }); 
    } 
} 
+0

太謝謝你了@裂解。感謝您提供示例代碼:) –