iOS:使用NSNotificationCenter在userInfo中发布代码块?
我可以安全地在程序地址空间中发布包含代码块的消息吗?测试有效,但这合法吗iOS:使用NSNotificationCenter在userInfo中发布代码块?,ios,objective-c,objective-c-blocks,Ios,Objective C,Objective C Blocks,我可以安全地在程序地址空间中发布包含代码块的消息吗?测试有效,但这合法吗 typedef void (^EmitBlock)(NSDictionary* args); - (void) subscribe { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(on_emit:) name:kEmit object:nil]; } - (void) on_emit:(N
typedef void (^EmitBlock)(NSDictionary* args);
- (void) subscribe {
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(on_emit:) name:kEmit object:nil];
}
- (void) on_emit:(NSNotification*) notification
{
EmitBlock completion = [[notification userInfo] valueForKey:@"completion"];
completion(@{@"result" : @"Ok"});
}
- (void) post:(EmitBlock) completion {
[[NSNotificationCenter defaultCenter] postNotificationName:kEmit
object:nil userInfo:@{@"completion":
^(NSDictionay* args) { NSLog(@"%@", args); }
}];
}
您可以使用库中的一个,例如使用带有通知的块
我认为更安全的方法是块是Objective-C对象,所以您可以将它们放入字典并使用它们 在通知的用户信息中 但请注意,根据以下数据: …将堆栈“向下”传递到中时,仍然需要使用
[^{}copy]
arrayWithObjects:
和其他执行保留操作的方法
应将块的副本放入字典:
[[NSNotificationCenter defaultCenter] postNotificationName:@"kEmit"
object:nil
userInfo:@{
@"completion" : [^(NSDictionary* args) { NSLog(@"%@", args); } copy]
}
];
CLFBlockNotification只是“简化”,每个代码块都需要订阅/取消订阅代码。我需要一个接收器上的订阅/取消订阅,代码块分布在所有代码中,在发送逻辑需要它们的地方声明。