Assign a variable inside a Block to a variable outside a Block
我收到了一个错误
Variable is not assignable (missing __block type specifier)
在
1 2 3 4 5 6 7 8 9 10 11 12 | Person *aPerson = nil; [participants enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { Person *participant = (Person*)obj; if ([participant.gender isEqualToString:@"M"]) { aPerson = participant; *stop = YES; } }]; return aPerson; |
您需要使用以下代码行来解决您的问题:
1 | __block Person *aPerson = nil; |
有关更多详细信息,请参阅本教程:块和变量
只是提醒我自己也犯了一个错误
1 | __block |
声明必须在首次声明变量时完成,即块的OUTSIDE,而不是它的内部。这应该解决关于变量不在块之外保留其值的注释中提到的问题。
只需使用
例如:
1 2 3 | __block Person *aPerson = nil; __block NSString *name = nil; |
1 | __block Person *aPerson = nil; |
要在块外部分配一个变量,在块之外总是使用__block说明符,那么代码应该是这样的: -
1 | __block Person *aPerson = nil; |
yes block是最常用的功能,所以为了避免保留周期,我们应该避免使用强变量,包括块内的self,尽管使用_weak或weakself。
如果您收到有关保留周期的任何警告,请尝试
1 2 | Person *strongPerson = [Person new]; __weak Person *weakPerson = person; |
现在您可以在块内引用