如何在Swift中将观察者添加到默认通知中心?我正在尝试移植这行代码,以便在电池电量发生变化时发送通知.
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
Run Code Online (Sandbox Code Playgroud) 我试图让使用的一个实例NSNotificationCenter与addObserver和postNotificationName,但我不能工作了,为什么它不会工作.
我有2行代码来添加观察者并在2个不同的类中发送消息
[[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(newEventLoaded:) name:@"Event" object:nil];
Run Code Online (Sandbox Code Playgroud)
和
[[NSNotificationCenter defaultCenter]postNotificationName:@"Event" object:self];
Run Code Online (Sandbox Code Playgroud)
如果我将名称设置为nil它工作正常,因为它只是一个广播,当我尝试定义通知名称时,消息永远不会通过.