【发布时间】:2016-05-25 07:38:37
【问题描述】:
在我的iOS 应用程序中,我发布了一个NSNotification 并在我的主线程UIView 之一中捕获它。我想与通知一起传递额外的信息。为此,我使用了 NSNotification 的 userInfo 字典。
[[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 次。我也在主线程中做一些动画。我在这里面临的问题是我的用户界面滞后。 UI 会以巨大的延迟响应滚动事件或触摸事件(我遇到了 1 到 2 秒的延迟)。经过一番研究,我知道NSDictionary 体积庞大,如果在主线程中使用会导致延迟。有没有其他方法可以通过 NSNotification 传递我的数据?
我尝试了另一种方法。我创建了一个自定义NSObject 类来保存我想要的数据,并将它作为postNotification 方法的对象参数传递。
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotifyValueComputedFromJS" object:customDataObject userInfo:nil];
这里的customDataObject 是我的自定义NSObject 类的一个实例。我知道该参数是通知的发送者(通常是自己)。如果我将自定义对象作为参数发送,这是一种错误的方法吗?
【问题讨论】:
标签: ios objective-c nsdictionary nsnotificationcenter nsnotification