gpt4 book ai didi

ios - 我不知道对于 objective-c 中的文字范围我应该避免什么样的 block 模式

转载 作者:技术小花猫 更新时间:2023-10-29 10:50:47 24 4
gpt4 key购买 nike

苹果的文档中是这样说的: block 文字(即 ^{ ... })是表示 block 的堆栈本地数据结构的地址。因此,堆栈本地数据结构的范围是封闭的复合语句,因此您应该避免以下示例中显示的模式:

void dontDoThis() {

void (^blockArray[3])(void); // an array of 3 block references

for (int i = 0; i < 3; ++i) {

blockArray[i] = ^{ printf("hello, %d\n", i); };

// WRONG: The block literal scope is the "for" loop.
}

//for example I invoke the block here
blockArray[1]();
}


void dontDoThisEither() {

void (^block)(void);

int i = random():

if (i > 1000) {

block = ^{ printf("got i at: %d\n", i); };

// WRONG: The block literal scope is the "then" clause.

}

// ...

}

我不知道应该避免哪些模式。似乎我可以调用与 block 定义具有相同文字范围的 block ,例如在“if”或“for”语句后面。你能帮我解释一下吗?

这是链接https://developer.apple.com/library/ios/#documentation/Cocoa/Conceptual/Blocks/Articles/bxUsing.html#//apple_ref/doc/uid/TP40007502-CH5-SW1

最佳答案

我认为指针的类比如下。

void foo() {
int *block = NULL;
{
int a;
block = &a;
}
// `block`, even though defined here, points to
// an invalid memory address.
}

一般来说, block 字面量本身只存在于定义它的 block 中,所以当离开那个 block 时,字面量就会消失(就像上面例子中的变量 a 所做的那样),然后你'剩下一个悬垂的指针。

出于这个原因, block 通常被复制到堆中以备将来使用。非 ARC 代码使用 block_copy 和 friend 。复制到堆中还会捕获您的 block 使用的所有相关变量(这可能会创建保留循环)。

在实践中,所有这些都被 ARC、属性和类的使用完全避开了。您在您的类中定义一个 copy 属性,然后将 block 分配给它。如果您让编译器生成 getter/setter,您的 block 文字将自动复制到堆中。

@interface Bla : NSObject
@property (nonatomic, copy) void (^blockProperty)(int i);
@endf

...

Bla *bla = [[Bla alloc] init];
{
bla.blockProperty = ^(int i) { printf("%d", i); };
}
// bla.blockProperty now points to a heap copy of the block literal from above,
// so it's not dangling.

关于ios - 我不知道对于 objective-c 中的文字范围我应该避免什么样的 block 模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13595406/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com