-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNSObjectAdditions.m
72 lines (57 loc) · 2.18 KB
/
NSObjectAdditions.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
//***************************************************************************
#import "NSObjectAdditions.h"
#include <pthread.h>
//***************************************************************************
@implementation NSObject (KVCThreading)
- (void)valueChangedForKey:(NSString*)key {
// pthread_main_np() appears to be undocumented on the Mac OS X manpages:
// it returns 1 if it's called from the main thread.
switch (pthread_main_np()) {
case 1:
[self willChangeValueForKey:key];
[self didChangeValueForKey:key];
break;
default:
[self performSelectorOnMainThread:@selector(willChangeValueForKey:)
withObject:key
waitUntilDone:YES];
[self performSelectorOnMainThread:@selector(didChangeValueForKey:)
withObject:key
waitUntilDone:YES];
break;
}
}
- (void)performSelectorOnMainThread:(SEL)aSelector
withObject:(id)argument1
withObject:(id)argument2
waitUntilDone:(BOOL)wait {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
NSInvocation* invocation =
[NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:aSelector]];
[invocation setSelector:aSelector];
[invocation setArgument:&argument1 atIndex:2];
[invocation setArgument:&argument2 atIndex:3];
[invocation retainArguments];
[self performSelectorOnMainThread:@selector(handleInvocation:)
withObject:invocation
waitUntilDone:wait];
[pool release];
}
- (void)handleInvocation:(NSInvocation*)anInvocation {
[anInvocation invokeWithTarget:self];
}
- (void)setValueOnMainThread:(id)value forKey:(NSString*)key {
switch (pthread_main_np()) {
case 1:
[self setValue:value forKey:key];
break;
default:
[self performSelectorOnMainThread:@selector(setValue:forKey:)
withObject:value
withObject:key
waitUntilDone:NO];
break;
}
}
@end
//***************************************************************************