본문 바로가기

프로그래밍/Swift

Closure Memory leak with Retain Cycle Examples

반응형

Objc

typedef void (^MyBlock)(void);
@property (nonatomic, copy) MyBlock block;

- (void)viewdidLoad {
  [super viewDidLoad];
  
  // Retain cycle
  self.block = ^{
    NSLog(@"%@", self.title);
  };
  
  
  // No retain cycle
  NSString *title = self.title;
  self.block = ^{
    NSLog(@"%@", title);
  };
  
  
  // No retain cycle
  @weakify(self);
  self.block = ^{
    @strongify(self);
    if (!self) {
      return;
    }
    NSLog(@"%@", self.title);
  };
  
  
  // No retain cycle
  [self closureWithCompletion:^{
    NSLog(@"%@", self.title);
  }];
  
  
}

 

Swift

var closure: (() -> Void)?

public func viewDidLoad() {
  super.viewDidLoad()
  
  // Retain cycle
  self.closure = {
    print(self.title)
  }
  
  
  // No retain cycle
  let title = self.title
  self.closure = {
    print(title)
  }
  
  
  // No retain cycle
  self.closure = { [weak self] in
    print(self?.title)
    // or
    guard let self else { return }
    print(self.title)
  }
  
  
  // No retain cycle
  self.closure(completion: {
    print(self.title)
  })
}
반응형