我可以更改通知中的用户信息吗

发布于 2024-12-20 10:21:18 字数 790 浏览 0 评论 0原文

我需要在目标 c 中创建可中断的钩子。如果任何钩子回调中断操作,可中断钩子应该能够中止操作。我想到使用 NSNotificationCenter 来实现类似的功能:

NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setObject: [NSNumber numberWithBool: NO] forKey: @"interrupted"];
[notificationCenter postNotificationName: @"Operation A will happen"
                                  object: self userInfo:userInfo];
if(![[userInfo objectForKey: @"interrupted"] boolValue])
{
    [self doOperationA];
}

并且在钩子方面

-(void) operationAWillHappen: (NSNotification *) note
{
    if(someCondition)
        [(NSMutableDictionary *)note.userInfo setObject:
         [NSNumber numberWithBool: YES] forKey: @"interrupted"];
}

我可以像这样更改用户信息吗?有没有更好的方法在 Objective C 中实现可中断钩子?

I need to create interruptible hooks in objective c. interruptible hooks should have the ability to abort an operation if any of the hooks callbacks interrupt the operation. I thought of using NSNotificationCenter for that like:

NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
[userInfo setObject: [NSNumber numberWithBool: NO] forKey: @"interrupted"];
[notificationCenter postNotificationName: @"Operation A will happen"
                                  object: self userInfo:userInfo];
if(![[userInfo objectForKey: @"interrupted"] boolValue])
{
    [self doOperationA];
}

and on the hook side

-(void) operationAWillHappen: (NSNotification *) note
{
    if(someCondition)
        [(NSMutableDictionary *)note.userInfo setObject:
         [NSNumber numberWithBool: YES] forKey: @"interrupted"];
}

Am I allowed to change the user info like that? is there a better way to implement interruptible hooks in objective c?

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

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

发布评论

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

评论(2

鼻尖触碰 2024-12-27 10:21:18

这是完全不安全的,如果这样做,您的应用程序可能会崩溃。

我认为您正在寻找的是“委托或委托模式。"

That's entirely unsafe and you'll probably crash your app if you do it.

I think what you're looking for is the "delegate or delegation pattern."

画中仙 2024-12-27 10:21:18

我的猜测是它可以工作,但由于 API 是一个不可变的对象,所以你不应该这样做。如果今天能正常工作,它可能会坏掉。

您始终可以在字典中传递 self,并让听众向其发送消息。

(我假设您想利用这样一个事实:您可以拥有任意数量的侦听器——委托要简单得多,但您只能获得一个委托。)

My guess is that it works but since the API is an immutable object, you're not supposed to. It could break if it happens to work today.

You could always pass self in the dictionary, and have listeners send it a message.

(I assume you want to take advantage of the fact that you can have an arbitrary number of listeners -- delegation is much simpler but you get only one delegate.)

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