使用 NSNotificationCenter 向另一个类发送通知

发布于 2024-11-26 01:11:04 字数 74 浏览 2 评论 0原文

所以我的目标是使用 NSNotificationCenter 向另一个类传递通知,我还想将带有通知的对象传递给另一个类,我应该怎么做?

So my goal is to deliver a notification to another class with using NSNotificationCenter, I also want to pass object with the notification to the other class, how should I do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

家住魔仙堡 2024-12-03 01:11:04

您必须首先注册一个通知名称

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLocating:) name:@"ForceUpdateLocation" object:nil]; // don't forget the ":"

,然后使用参数字典发布通知

[[NSNotificationCenter defaultCenter] postNotificationName:@"ForceUpdateLocation" object:self userInfo:[NSDictionary dictionaryWithObject:@"1,2,3,4,5" forKey:@"categories_ids"]]; 

,方法将是

- (void)startLocating:(NSNotification *)notification {

    NSDictionary *dict = [notification userInfo];
}

You must first register a notification name

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startLocating:) name:@"ForceUpdateLocation" object:nil]; // don't forget the ":"

And then post a notification with a dictionary of parameters

[[NSNotificationCenter defaultCenter] postNotificationName:@"ForceUpdateLocation" object:self userInfo:[NSDictionary dictionaryWithObject:@"1,2,3,4,5" forKey:@"categories_ids"]]; 

and the method will be

- (void)startLocating:(NSNotification *)notification {

    NSDictionary *dict = [notification userInfo];
}
画离情绘悲伤 2024-12-03 01:11:04

只需按照 此处,例如:

发布通知:

-(void)postNotificationName:(NSString *)notificationName
                     object:(id)notificationSender
                   userInfo:(NSDictionary *)userInfo;

其中 userInfo 是包含有用对象的字典。

另一方面注册通知:

-(void)addObserver:(id)notificationObserver
           selector:(SEL)notificationSelector
               name:(NSString *)notificationName
             object:(id)notificationSender;

您还可以检查Apple的 通知编程主题

Just call any method for posting notifications as described here, for instance :

to post a notification :

-(void)postNotificationName:(NSString *)notificationName
                     object:(id)notificationSender
                   userInfo:(NSDictionary *)userInfo;

where userInfo is a dictionary containing useful objects.

On the other side to register for notifications :

-(void)addObserver:(id)notificationObserver
           selector:(SEL)notificationSelector
               name:(NSString *)notificationName
             object:(id)notificationSender;

You could also check Apple's Notification Programming Topics.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文