我试图将我的app委托中的对象传递给另一个类中的通知接收器 .
我想传递整数 messageTotal
. 现在我有:
在接收器中:
- (void) receiveTestNotification:(NSNotification *) notification
{
if ([[notification name] isEqualToString:@"TestNotification"])
NSLog (@"Successfully received the test notification!");
}
- (void)viewDidLoad {
[super viewDidLoad];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(dismissSheet) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(receiveTestNotification:) name:@"eRXReceived" object:nil];
在正在进行通知的类中:
[UIApplication sharedApplication].applicationIconBadgeNumber = messageTotal;
[[NSNotificationCenter defaultCenter] postNotificationName:@"eRXReceived" object:self];
但我想将对象 messageTotal
传递给另一个类 .
4 回答
您必须使用“userInfo”变体并传递包含messageTotal整数的NSDictionary对象:
在接收端,您可以访问userInfo字典,如下所示:
在提供的解决方案的基础上,我认为显示一个传递您自己的自定义数据对象的示例可能会有所帮助(我在这里根据问题将其称为“消息”) .
Class A (sender):
Class B (receiver):
正如@Johan Karlsson指出的那样......我做错了 . 这是使用NSNotificationCenter发送和接收信息的正确方法 .
首先,我们查看postNotificationName的初始化程序:
source
我们将使用
userInfo
param传递我们的信息 .[NSObject : AnyObject]
类型是Objective-C的保留 . 因此,在Swift中,我们需要做的就是传入一个Swift字典,该字典包含从NSObject
派生的键和可以AnyObject
的值 .有了这些知识,我们就创建了一个字典,我们将其传递给
object
参数:然后我们将字典传递给我们的对象参数 .
Sender
Receiver Class
首先,我们需要确保我们的 class 正在观察通知
然后我们可以收到我们的字典:
斯威夫特4
奖金(你绝对应该这样做!):
将
Notification.Name("SomeNotificationName")
替换为.someNotificationName
:将
"key0"
和"key1"
替换为Notification.Key.key0
和Notification.Key.key1
:为什么我一定要这样做?为了避免代价高昂的拼写错误,享受重命名,享受使用等...