-
Notifications
You must be signed in to change notification settings - Fork 0
/
NSManagedObject+GTBitmask.m
93 lines (84 loc) · 2.44 KB
/
NSManagedObject+GTBitmask.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
//
// NSManagedObject+GTBitmask.m
//
// Created by Andrew Mackenzie-Ross on 17/12/10.
//
#import "NSManagedObject+GTBitmask.h"
#import "GTBitmask.h"
#import <objc/objc-runtime.h>
@implementation NSManagedObject (GTBitmaskAdditions)
static NSMutableArray *bitmasks;
- (void) findBitmaskIvars {
bitmasks = [[NSMutableArray alloc] init];
unsigned int count;
Ivar* ivars = class_copyIvarList([self class], &count);
for(unsigned int i = 0; i < count; ++i)
{
NSString *ivarName = [NSString stringWithCString:ivar_getName(ivars[i]) encoding:NSASCIIStringEncoding];
id ivar = [self valueForKey:ivarName];
if ([ivar class] == [GTBitmask class]) {
[bitmasks addObject:ivarName];
}
}
free(ivars);
}
- (id) valueForUndefinedKey:(NSString *)key {
// find bitmask ivars
if (!bitmasks) {
[self findBitmaskIvars];
}
// search for key and return value
BOOL boolValue;
BOOL keyfound = NO;
for ( NSString *ivarName in bitmasks) {
GTBitmask *bitmask = [self valueForKey:ivarName];
for (NSString *bitmaskKey in bitmask.keys) {
if ([bitmaskKey isEqualToString:key]) {
keyfound = YES;
[self willAccessValueForKey:bitmask.coreDataAttributeKey];
[self willAccessValueForKey:key];
boolValue = [bitmask boolValueForKey:key];
[self didAccessValueForKey:bitmask.coreDataAttributeKey];
[self didAccessValueForKey:key];
break;
}
}
}
if (!keyfound) {
NSException *exception = [NSException exceptionWithName:@"Undefined Key"
reason:@"No value for key found"
userInfo:nil];
@throw exception;
}
return [NSNumber numberWithBool:boolValue];
}
- (void) setValue:(id)value forUndefinedKey:(NSString *)key {
// find bitmask ivars
if (!bitmasks) {
[self findBitmaskIvars];
}
// search for key and save
BOOL keyfound = NO;
for ( NSString *ivarName in bitmasks) {
GTBitmask *bitmask = [self valueForKey:ivarName];
for (NSString *bitmaskKey in bitmask.keys) {
if ([bitmaskKey isEqualToString:key]) {
keyfound = YES;
[self willChangeValueForKey:key];
[bitmask setBoolValue:[(NSNumber*)value boolValue] ForKey:key];
[self setValue:bitmask.bitmask forKey:bitmask.coreDataAttributeKey];
[bitmask clean];
[self didChangeValueForKey:key];
break;
}
}
}
if (!keyfound) {
NSException *exception = [NSException exceptionWithName:@"Undefined Key"
reason:@"No value for key found"
userInfo:nil];
@throw exception;
}
return;
}
@end