[英]weakSelf in enumerateObjectsUsingBlock?
Should I use a weakSelf, when calling self in the following code snippit (self.searchResults): 我应该使用weakSelf,在以下代码中调用self时snippit(self.searchResults):
[self.restaurants enumerateObjectsUsingBlock:^(Restaurant *restaurant, NSUInteger idx, BOOL *stop) {
if ([scope isEqualToString:@"All"] || [restaurant.name isEqualToString:scope]) {
NSRange range = [restaurant.name rangeOfString:searchText
options:(NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch)];
if (range.length > 0) {
[self.searchResults addObject:restaurant];
}
}
}];
Should I refer to weak, when calling self.searchResults in the block ? 当我在块中调用self.searchResults时,我应该引用弱吗?
weak
is not required here. 这里不需要
weak
。 The intent of using weak
for variables copied into a block is to avoid a circular reference, and you're not at risk of that here - in part because the block isn't held onto. 对于复制到块中的变量使用
weak
的意图是避免使用循环引用,并且您在此处没有风险 - 部分原因是该块未被保留。
Consider the following example. 请考虑以下示例。 Capturing self in the block which is owned by self causes a retain cycle that cannot be broken:
在由self拥有的块中捕获self会导致无法打破的保留周期:
@interface MyObject : NSObject
@property (copy, nonatomic) void (^contrived)();
@end
@implementation MyObject
- (id) init
{
self = [super init];
if ( self )
{
self.contrived = ^{
NSLog( @"%@", self.description );
};
}
return self;
}
@end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.