我可以更改通知中的用户信息吗
我需要在目标 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是完全不安全的,如果这样做,您的应用程序可能会崩溃。
我认为您正在寻找的是“委托或委托模式。"
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."
我的猜测是它可以工作,但由于 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.)