arango_86
arango_86

Reputation: 4425

__weak + __block is it Ok to use both for a variable

In ARC, the following line of code is meaningful? Please confirm.

__block __weak MyViewController_iPad *blockSelf = self;

This is not throwing any errors. Don't know why.

Consider the following example.

NSArray* keyWords = someArray;

[keyWords enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                keyWords = nil;
            }];

In this case do we need to specify both attributes under ARC. This is unusual thats why I had this doubt.

__weak __block NSArray* keyWords = someArray;

[keyWords enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    keyWords = nil;
                }];

The above code snippet is correct? Please confirm.

Upvotes: 0

Views: 228

Answers (2)

Rob
Rob

Reputation: 437592

In your edit, you provided some sample code:

__weak __block NSArray* keyWords = someArray;

[keyWords enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
    keyWords = nil;
}];

In this situation __weak is neither needed nor appropriate. Typically you use __weak in conjunction with blocks to avoid strong reference cycles. But no such cycle exists here, so __weak is not needed.

Just use __block, remove __weak, and you're done.

(Having said that, this example represents other issues, namely that you really shouldn't be changing keyWords while enumerating through the array. If you tell us what you're trying to do with this code we can undoubtedly show you a better way to achieve it.)

Upvotes: 2

user3432164
user3432164

Reputation:

You should use __block if you want to change variable value in block.

e.g:

__block BOOL result = NO;
dispatch_sync(dispatch_get_main_queue(), ^{
  ...
  result = YES;
  ...
});

You should use __weak if you want to avoid retain cycles.

e.g.

__weak typeof(self) wself = self;
self.foobarCompletion = ^{
  ...
  wself.foo = YES;
  ...
};

You can combine them if there is a need.

Upvotes: 3

Related Questions