Say I have something like this:
@interface Foo : UIViewController
@property (nonatomic, strong) NSString *name;
@end
@implementation Foo
- (void)viewDidLoad
{
[super viewDidLoad];
_name = @"Me";
NSArray *blackList = @[@"John", @"Malcolm", @"Jimmy"];
[blackList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isEqualToString:_name]) // Is _name just as bad as using self.name?
{
NSLog(@"You're on the blacklist!");
*stop = YES;
}
}];
}
@end
The question is on this line: if ([obj isEqualToString:_name])
I know it's bad to refer to self inside a block, and you can get around it by using __weak Foo *weakSelf = self
and then refer to weakSelf
in the block.
__weak Foo *weakSelf = self;
[blackList enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
if ([obj isEqualToString:weakSelf.name])
{
NSLog(@"You're on the blacklist!");
*stop = YES;
}
}];
However, is this still bad if we don't explicitly write self.name
, but write _name
?
Is
_name
just as bad as usingself.name
?
Yes, it is. In fact, self
reference is still there - the compiler inserts it for you.
you can get around it by using
__weak Foo *weakSelf = self
and then refer toweakSelf
in the block.
You can use the same trick here by referring to weakSelf->_name
Note: It is not necessary to use this trick with enumerateObjectsUsingBlock:
, because the enumeration finishes and the block gets released in the scope of your method. A threat of retain cycle happens only when you put the block in a variable on the self
object, while also referring to self
from the block.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments