-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNSObject+DeallocBlock.mm
95 lines (70 loc) · 1.99 KB
/
NSObject+DeallocBlock.mm
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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
//
// author: fabrice truillot de chambrier
//
// © 2011-2015, men in silicium sàrl
//
#import "OS/NSObject+DeallocBlock.h"
#import "OS/NSObject+AssociatedObject.h"
#import <objc/runtime.h>
@interface MDeallocBlock : NSObject
@property ( readwrite, nonatomic ) dispatch_queue_t queue;
@property ( readwrite, nonatomic, copy ) dispatch_block_t block;
@end
@implementation NSObject (DeallocBlock)
- (void) addDeallocBlock: (dispatch_block_t) block
{
[self addDeallocBlockOnQueue: nil block: block];
}
- (void) addDeallocBlockOnQueue: (dispatch_queue_t) queue block: (dispatch_block_t) block
{
@synchronized( self )
{
NSMutableArray* deallocBlocks = (NSMutableArray*) [self associatedObjectForRawKey: @selector(deallocBlocks)];
if ( deallocBlocks == nil )
{
deallocBlocks = [NSMutableArray new];
[self setAssociatedObject: deallocBlocks forRawKey: @selector(deallocBlocks) policy: OBJC_ASSOCIATION_RETAIN];
}
MDeallocBlock* deallocBlock = [MDeallocBlock new];
deallocBlock.queue = queue;
deallocBlock.block = block;
[deallocBlocks addObject: deallocBlock];
}
}
- (dispatch_block_t) removeLastDeallocBlock
{
@synchronized( self )
{
NSMutableArray* deallocBlocks = (NSMutableArray*) [self associatedObjectForRawKey: @selector(deallocBlocks)];
if ( deallocBlocks == nil ) return nil;
if ( deallocBlocks.count == 0 ) return nil;
dispatch_block_t block = deallocBlocks.lastObject;
[deallocBlocks removeObject: block];
return block;
}
}
- (NSArray*) deallocBlocks
{
@synchronized( self )
{
NSArray* deallocBlocks = (NSArray*) [self associatedObjectForRawKey: @selector(deallocBlocks)];
NSMutableArray* blocks = [NSMutableArray new];
for ( MDeallocBlock* deallocBlock in deallocBlocks ) {
[blocks addObject: deallocBlock.block];
}
return [blocks copy];
}
}
@end
@implementation MDeallocBlock
- (void) dealloc
{
if ( self.block == nil ) return;
if ( self.queue == nil ) {
self.block();
}
else {
dispatch_async( self.queue, self.block );
}
}
@end