我正在尝试将一个对象从我的应用程序委托传递到另一个类中的通知接收器。
我想要传递整数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
传递给另一个类。
发布于 2011-10-26 06:42:41
您必须使用"userInfo“变体并传递一个包含messageTotal整数的NSDictionary对象:
NSDictionary* userInfo = @{@"total": @(messageTotal)};
NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];
在接收端,您可以访问userInfo字典,如下所示:
-(void) receiveTestNotification:(NSNotification*)notification
{
if ([notification.name isEqualToString:@"TestNotification"])
{
NSDictionary* userInfo = notification.userInfo;
NSNumber* total = (NSNumber*)userInfo[@"total"];
NSLog (@"Successfully received test notification! %i", total.intValue);
}
}
发布于 2016-12-29 00:31:15
Swift 5
func post() {
NotificationCenter.default.post(name: Notification.Name("SomeNotificationName"),
object: nil,
userInfo:["key0": "value", "key1": 1234])
}
func addObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(someMethod),
name: Notification.Name("SomeNotificationName"),
object: nil)
}
@objc func someMethod(_ notification: Notification) {
let info0 = notification.userInfo?["key0"]
let info1 = notification.userInfo?["key1"]
}
奖励(你绝对应该这么做!):
用.someNotificationName
替换Notification.Name("SomeNotificationName")
extension Notification.Name {
static let someNotificationName = Notification.Name("SomeNotificationName")
}
将"key0"
和"key1"
替换为Notification.Key.key0
和Notification.Key.key1
extension Notification {
enum Key: String {
case key0
case key1
}
}
为什么我一定要这么做呢?为了避免代价高昂的打字错误,享受重命名,享受查找用法等。
https://stackoverflow.com/questions/7896646
复制相似问题