我对使用 block 还很陌生。我想知道是否有办法将代码动态添加到 block 中?如果你愿意的话,一个可变 block 。
最佳答案
这听起来并不完全像您想要的那样,但即使不完全相同,它也能实现类似的结果:具有要从外部 block 中顺序调用的 block 的 __block NSMutableArray
。
一个愚蠢的演示:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[])
{
@autoreleasepool {
__block NSMutableArray *subblocks = [NSMutableArray array];
void (^blockWithBlocks)(void) = ^{
NSLog(@"%s: in blockWithBlocks()", __PRETTY_FUNCTION__);
for (void (^subblock)(void) in subblocks) {
subblock();
}
};
for (int i = 0; i < 3; i++) {
void (^subblock)(void) = ^{
NSLog(@"%s: in subblock %d", __PRETTY_FUNCTION__, i);
};
[subblocks addObject:subblock];
}
blockWithBlocks();
}
return 0;
}
请注意,在 ARC 下复制 block 的要求一直在变化。以前有必要编写 [subblocks addObject:[subblock copy]];
而不是简单地 [subblocks addObject:subblock];
在 the clang documentation < 中描述的当前语义下/p>
With the exception of retains done as part of initializing a __strong parameter variable or reading a __weak variable, whenever these semantics call for retaining a value of block-pointer type, it has the effect of a Block_copy. The optimizer may remove such copies when it sees that the result is used only as an argument to a call.
唯一需要复制 block 以确保它不再在堆栈中的情况是当 block 作为参数传递给具有 __strong
的函数/方法时> 参数变量以及何时从 __weak
变量中读取 block 。
关于objective-c - 添加代码以动态阻止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14076145/