Weak links in blocks and save loops

In this question, I asked about the following code and saved the loops:

__weak Cell *weakSelf = self;
NSBlockOperation *op = [NSBlockOperation blockOperationWithBlock:^{
        UIImage *image = /* render some image */
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            [weakSelf setImageViewImage:image];
        }];
    }];
    [self.renderQueue addOperation:op];

All answers state that using a weak link was not necessary here, as this code does not lead to a save loop. However, experimenting with some other code, the following leads to a save loop (unless I use a weak link, the current view controller is not freed)

    //__weak ViewController *weakSelf = self;
    MBItem *close = [[MBItem alloc] initWithBlock:^{
        [self dismissModalWithDefaultAnimation:NO];
    }];
    NSMutableArray *items = [[NSMutableArray alloc] initWithObjects:close, nil];
    [self.childObject setItems:items];

Why does the second result lead to a save cycle, but not to the first?

+5
source share
2 answers

Your old code creates this save loop if you are not using__weak :

  • (NSBlockOperation *)op save external block
  • The external block saves self(if you are not using __weak)
  • self (NSOperationQueue *)renderQueue
  • (NSOperationQueue *)renderQueue (NSBlockOperation *)op

, . , , . op , renderQueue , .

, :

  • (MBItem *)close
  • self
  • self childObject
  • childObject (NSMutableArray *)items
  • (NSMutableArray *)items (MBItem *)close

, , . , . , (, childObject.items), __weak .

+12

, MBItem, .

, , self :

[startSomeOperationWithCompletionBlock:^{
    [self doSomeThing];
}];

self, self , . ( ) .

, , , self , , , , :

__weak MyClass *weakSelf = self;
[startSomeOperationWithCompletionBlock:^{
    MyClass *strongSelf = weakSelf;
    if (strongSelf) {
        [strongSelf doSomeThing];
    }
}];

self, self . weakSelf nil . , , , weakSelf . ( , nil .)

strongSelf self .

+8

All Articles