块数组? [英] An Array of Blocks?

查看:72
本文介绍了块数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对我来说,这似乎是一种非常奇怪的互动,但同时它不仅有效,而且在此过程中不会发出任何警告或错误.只是希望对一般的块有更好的了解,以及为什么这样的事情是对还是错.

This seems like a very strange interaction to me but at the same time it not only works but throws no warnings or errors in the process. Just looking to get some better understanding of blocks in general and why something like this could be right or wrong.

有什么理由不应该这样做吗?

Is there any reason why something like this shouldn't be done?

NSArray *array = [NSArray arrayWithObjects:^{NSLog(@"Block 1");}, ^{NSLog(@"Block 2");}, ^{NSLog(@"Block 3");}, nil];

for (id block in array) {
    [block invoke];
}

推荐答案

将块放入NSArray中就可以了;他们是对象.实际上,它们是从NSObject继承的.

Putting Blocks into NSArrays is fine; they're objects. In fact, they inherit from NSObject.

但是,您确实需要复制它们.这些块是在堆栈上创建的,需要移到堆中,以驻留在当前方法的末尾.如果您使用的是ARC,这很容易:

You do need to copy, them, however. Those Blocks are created on the stack and need to be moved to the heap in order to live past the end of the current method. If you're using ARC, this is easy:

NSArray *array = [NSArray arrayWithObjects:[^{NSLog(@"Block 1");} copy], ...

在MRR下,您需要平衡copy,因此有两个不愉快的选择:使用临时文件,或在创建数组后立即枚举数组并将release发送给其所有成员.

Under MRR, you need to balance that copy, so you have two unpleasant options: use temps, or enumerate the array right after creating it and send release to all its members.

另一方面,发送invoke并不完全符合要求,因为这是一种私有方法.调用功能块的唯一完全符合API的方法是使用函数调用语法:

Sending invoke, on the other hand, isn't completely kosher, because that's a private method. The only fully-API-compliant way to invoke a Block is with function-call syntax:

typedef GenericBlock dispatch_block_t;
for( GenericBlock block in array ){
    block();
}

这篇关于块数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆