forked from overtake/telegram
-
Notifications
You must be signed in to change notification settings - Fork 6
/
NSObject+TGLock.m
73 lines (57 loc) · 1.31 KB
/
NSObject+TGLock.m
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
#import "NSObject+TGLock.h"
#import <objc/runtime.h>
static const char *lockPropertyKey = "TLObjectLock::lock";
@interface TLObjectLockImpl : NSObject
{
TG_SYNCHRONIZED_DEFINE(objectLock);
}
- (void)tgTakeLock;
- (void)tgFreeLock;
@end
@implementation TLObjectLockImpl
- (id)init
{
self = [super init];
if (self != nil)
{
TG_SYNCHRONIZED_INIT(objectLock);
}
return self;
}
- (void)tgTakeLock
{
TG_SYNCHRONIZED_BEGIN(objectLock);
}
- (void)tgFreeLock
{
TG_SYNCHRONIZED_END(objectLock);
}
@end
@implementation NSObject (TGLock)
- (void)tgLockObject
{
TLObjectLockImpl *lock = (TLObjectLockImpl *)objc_getAssociatedObject(self, lockPropertyKey);
if (lock == nil)
{
@synchronized(self)
{
lock = [[TLObjectLockImpl alloc] init];
objc_setAssociatedObject(self, lockPropertyKey, lock, OBJC_ASSOCIATION_RETAIN);
}
}
[lock tgTakeLock];
}
- (void)tgUnlockObject
{
TLObjectLockImpl *lock = (TLObjectLockImpl *)objc_getAssociatedObject(self, lockPropertyKey);
if (lock == nil)
{
@synchronized(self)
{
lock = [[TLObjectLockImpl alloc] init];
objc_setAssociatedObject(self, lockPropertyKey, lock, OBJC_ASSOCIATION_RETAIN);
}
}
[lock tgFreeLock];
}
@end