728x90
반응형
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)
})
}
반응형
'프로그래밍 > Swift' 카테고리의 다른 글
swift-format 에러발생 (0) | 2022.09.21 |
---|---|
swift와 objc에서 순환참조 처리하기 (0) | 2022.08.02 |
objc에서 swift 파일 임포트 (0) | 2022.07.28 |
pod install 에러 (rescue in block in activate_dependencies': Could not find 'minitest' (>= 5.1) among 39 total gem(s)) (0) | 2022.07.09 |
iOS 개발자 되는 방법 (0) | 2022.01.18 |