ios在字典或数组中存储^块? [英] ios store ^block in dictionary or array?
问题描述
我可以将^块存储在字典或数组中吗?
Can I store ^block in a dictionary or an array?
我需要收听服务器通知,我需要提供一个块来处理通知,在我的项目中,几个视图控制器都希望听到通知,所以我创建了一个通用的通知管理器,它有自己的块来处理服务器通知,它有一个委托数组,所以在管理器的块中:
I need to listen to a server notification which I need to provide a block to handle the notification, and in my project several view controllers all want to hear the notification, so I made a generic notification manager, which has its own block for handling server notification and it has an array of delegates, so in the manager's block:
- (^)(NSString *message){
for (delegate in allDelegates)
{
delegate.handlerBlock(message);
}
}
但是我可以在一个集合中存储块吗?
but can I store blocks in a collection?
推荐答案
您可以将对象存储到集合中。但要注意范围:当它们被排除在功能范围之外时复制它们。这是你的情况,因为你将它们存储在一个数组中。
You can store object into collection. But take care of the scope: Copy them when they will be kept out of a function scope. This is your case since you are storing them in a array.
[NSArray arrayWithObject:
[[^{ NSLog(@"block 1"); } copy] autorelease],
[[^{ NSLog(@"block 2"); } copy] autorelease], nil]
在ARC上,你仍然需要告诉它你绝对需要复制你的块。它应该在释放数组时释放块。
On ARC, you still need to tell it you absolutely needs to copy your block. It should release the block when the array is freed.
[NSArray arrayWithObject:
[^{ NSLog(@"block 1"); } copy],
[^{ NSLog(@"block 2"); } copy], nil]
这篇关于ios在字典或数组中存储^块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!