iOS block备忘录02

循环引用的问题

让我们先来看一段代码。

1
2
3
4
@interface MyClass ()
@property (readonly) int val;
@property (strong) dispatch_block_t work;
@end

Capturing self strongly in this block is likely to lead to a retain cycle

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
@interface BlockTestView2 ()

@property (readonly) int val;
@property (nonatomic, strong) id obj;

@property (strong) dispatch_block_t work;

@end

@implementation BlockTestView2

- (instancetype)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
_obj = @1;
[self setup];
}

return self;
}

- (void)setup {
_val = 5;

// retain cycle
self.work = ^{
NSLog(@"BlockTestView2 %d", _val);
};
}

// 1. Scoping
// Avoid capturing self
- (void)setup1 {
int local = self.val;
self.work = ^{
NSLog(@"BlockTestView2 %d", local);
};
}

// 2. Programmatically
// nil the block property
- (void)setup2 {
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Warc-retain-cycles"
self.work = ^{
NSLog(@"BlockTestView2 %d", _val);
};
#pragma clang diagnostic pop

// nil the block property somewhere, please ignore
// this call at this point
[self cancel];
}
- (void)cancel {
self.work = nil;
}

// 3. Attributes
// Use __weak
- (void)setup3 {
__weak __typeof(self) weakSelf = self;
self.work = ^{
__strong __typeof(self) strongSelf = weakSelf;
NSLog(@"BlockTestView2 %@", strongSelf.obj);
};
}

@end
坚持原创技术分享,您的支持将鼓励我继续创作!