본문 바로가기

프로그래밍/Swift

swift와 objc에서 순환참조 처리하기

반응형

순환참조는 메모리누수를 발생시킬 수 있다. 따라서 weak reference를 통해 순환참조를 피할 수 있다.

 

예시

Swift

func retainCycleHandler() {
    someObject.someBlock { [weak self] in
    	guard let self = self else { return }
        self.navigationController?.popViewController(animated: true)
    }
}

 

objc

- (void)retainCycleHander {
    __weak __typeof(self)weakSelf = self;
    [someObject someBlock:^ {
        __strong __typeof(weakSelf)self = weakSelf;
        if (!self) { return; }
        [self.navigationController popViewControllerAnimated:YES];
    }];
}

 

https://github.com/jspahrsummers/libextobjc 같은 라이브러리에는 @weakfy, @strongify로 더 간단하게 디파인 되어있다.

- (void)retainCycleHander {
    @weakfy(self);
    [someObject someBlock:^ {
    	@strongify(self);
        if (!self) { return; }
        [self.navigationController popViewControllerAnimated:YES];
    }];
}
반응형