在我的iOS
應用程序中,我發佈NSNotification
並在主線程中將其捕獲到我的UIView
之一中。我想傳遞額外的信息和通知。我使用userInfo
字典NSNotification
。NSNotificationCenter 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
類的一個實例。我知道這個參數是通知的發送者(通常它會是自己的)。如果我將自定義對象作爲參數發送,這是錯誤的方法嗎?
太謝謝你了@裂解。感謝您提供示例代碼:) –