将块内的变量分配给块外的变量
我收到错误
变量不可分配(缺少 __block 类型说明符)
aPerson = attendee;
行上的 。如何确保块可以访问 aPerson
变量并且可以返回 aPerson
变量?
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;
I'm getting an error
Variable is not assignable (missing __block type specifier)
on the line aPerson = participant;
. How can I make sure the block can access the aPerson
variable and the aPerson
variable can be returned?
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
您需要使用这行代码来解决您的问题:
有关更多详细信息,请参阅本教程:块和变量
You need to use this line of code to resolve your problem:
For more details, please refer to this tutorial: Blocks and Variables
只是提醒我自己也犯过一个错误,
必须在第一次声明变量时进行声明,即在块的外部,而不是在块的内部。这应该可以解决注释中提到的有关变量不保留其值在块之外的问题。
Just a reminder of a mistake I made myself too, the
declaration must be done when first declaring the variable, that is, OUTSIDE of the block, not inside of it. This should resolve problems mentioned in the comments about the variable not retaining its value outside of the block.
只需使用 __block 前缀即可在块内声明和分配任何类型的变量。
例如:
Just use the
__block
prefix to declare and assign any type of variable inside a block.For example:
要在块内分配一个在块外的变量,始终在该变量之前使用 __block 说明符,您的代码应如下所示:-
To assign a variable inside block which outside of block always use __block specifier before that variable your code should be like this:-
当我看到同样的错误时,我尝试像这样解决它:
并且它工作正常
只需在变量之前添加“__block”。
When I saw the same error, I tried to resolve it like:
and its working fine
Just add "__block" before Variable.
如果您收到有关保留周期的任何警告,请尝试
__weak
,否则使用__block
现在您可以在块内引用
weakPerson
对象。Try
__weak
if you get any warning regarding retain cycle else use__block
Now you can refer
weakPerson
object inside block.yes 块是最常用的功能,因此为了避免保留循环,我们应该避免使用强变量,包括块内的 self,尽管使用 _weak 或weakself。
yes block are the most used functionality , so in order to avoid the retain cycle we should avoid using the strong variable,including self inside the block, inspite use the _weak or weakself.