Frage

Should I use a weakSelf, when calling self in the following code 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 ?

War es hilfreich?

Lösung

weak is not required here. 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.

Consider the following example. Capturing self in the block which is owned by self causes a retain cycle that cannot be broken:

@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
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top