forked from snej/MYUtilities
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMYDynamicObject.m
620 lines (532 loc) · 20.8 KB
/
MYDynamicObject.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//
// MYDynamicObject.m
// MYUtilities
//
// Created by Jens Alfke on 8/6/09.
// Copyright 2009 Jens Alfke. All rights reserved.
//
#import "MYDynamicObject.h"
#import "MYLogging.h"
#import "Test.h"
#import <ctype.h>
#import <objc/runtime.h>
#ifdef __IPHONE_OS_VERSION_MIN_REQUIRED
#define USE_BLOCKS (__IPHONE_OS_VERSION_MIN_REQUIRED >= 50000)
#else
#define USE_BLOCKS (MAC_OS_X_VERSION_MIN_REQUIRED >= 1070)
#endif
DefineLogDomain(Model);
@implementation MYDynamicObject
// Abstract implementations for subclasses to override:
- (id) getValueOfProperty: (NSString*)property {
NSAssert(NO, @"No such property %@.%@", [self class], property);
return nil;
}
- (BOOL) setValue: (id)value ofProperty: (NSString*)property {
return NO;
}
#pragma mark - SELECTOR-TO-PROPERTY NAME MAPPING:
NS_INLINE BOOL isGetter(const char* name) {
if (!name[0] || name[0]=='_' || name[strlen(name)-1] == ':')
return NO; // If it has parameters it's not a getter
if (strncmp(name, "get", 3) == 0)
return NO; // Ignore "getXXX" variants of getter syntax
return YES;
}
NS_INLINE BOOL isSetter(const char* name) {
return strncmp("set", name, 3) == 0 && name[strlen(name)-1] == ':';
}
// IDEA: to speed this code up, create a map from SEL to NSString mapping selectors to their keys.
// converts a getter selector to an NSString, equivalent to NSStringFromSelector().
NS_INLINE NSString *getterKey(SEL sel) {
return [NSString stringWithUTF8String:sel_getName(sel)];
}
// converts a setter selector, of the form "set<Key>:" to an NSString of the form @"<key>".
NS_INLINE NSString *setterKey(SEL sel, BOOL upperCase) {
const char* name = sel_getName(sel) + 3; // skip past 'set'
size_t length = strlen(name);
char buffer[1 + length];
strcpy(buffer, name);
if (!upperCase)
buffer[0] = (char)tolower(buffer[0]); // lowercase the property name
buffer[length - 1] = '\0'; // and remove the ':'
return [NSString stringWithUTF8String:buffer];
}
+ (NSString*) getterKey: (SEL)sel {return getterKey(sel);}
+ (NSString*) setterKey: (SEL)sel {return setterKey(sel, NO);}
#pragma mark - GENERIC ACCESSOR METHOD IMPS:
#if USE_BLOCKS
static inline void setIdProperty(MYDynamicObject *self, NSString* property, id value) {
BOOL result = [self setValue: value ofProperty: property];
NSCAssert(result, @"Property %@.%@ is not settable", [self class], property);
}
#else
static id getIdProperty(MYDynamicObject *self, SEL _cmd) {
return [self getValueOfProperty: getterKey(_cmd)];
}
static void setIdProperty(MYDynamicObject *self, SEL _cmd, id value) {
NSString* property = setterKey(_cmd, NO);
BOOL result = [self setValue: value ofProperty: property];
NSCAssert(result, @"Property %@.%@ is not settable", [self class], property);
}
static int getIntProperty(MYDynamicObject *self, SEL _cmd) {
return [getIdProperty(self,_cmd) intValue];
}
static void setIntProperty(MYDynamicObject *self, SEL _cmd, int value) {
setIdProperty(self, _cmd, [NSNumber numberWithInt:value]);
}
static unsigned int getIntProperty(MYDynamicObject *self, SEL _cmd) {
return [getIdProperty(self,_cmd) unsignedIntValue];
}
static void setUnsignedIntProperty(MYDynamicObject *self, SEL _cmd, unsigned int value) {
setIdProperty(self, _cmd, [NSNumber numberWithUnsignedInt:value]);
}
static long getLongProperty(MYDynamicObject *self, SEL _cmd) {
return [getIdProperty(self,_cmd) longValue];
}
static void setLongProperty(MYDynamicObject *self, SEL _cmd, long value) {
setIdProperty(self, _cmd, [NSNumber numberWithLong:value]);
}
static unsigned long getUnsignedLongProperty(MYDynamicObject *self, SEL _cmd) {
return [getIdProperty(self,_cmd) unsignedLongValue];
}
static void setUnsignedLongProperty(MYDynamicObject *self, SEL _cmd, unsigned long value) {
setIdProperty(self, _cmd, [NSNumber numberWithUnsignedLong:value]);
}
static long long getLongProperty(MYDynamicObject *self, SEL _cmd) {
return [getIdProperty(self,_cmd) longLongValue];
}
static void setLongLongProperty(MYDynamicObject *self, SEL _cmd, long long value) {
setIdProperty(self, _cmd, [NSNumber numberWithLongLong:value]);
}
static unsigned long long getUnsignedLongProperty(MYDynamicObject *self, SEL _cmd) {
return [getIdProperty(self,_cmd) unsignedLongLongValue];
}
static void setUnsignedLongProperty(MYDynamicObject *self, SEL _cmd, unsigned long long value) {
setIdProperty(self, _cmd, [NSNumber numberWithUnsignedLongLong:value]);
}
static bool getBoolProperty(MYDynamicObject *self, SEL _cmd) {
return [getIdProperty(self,_cmd) boolValue];
}
static void setBoolProperty(MYDynamicObject *self, SEL _cmd, bool value) {
setIdProperty(self, _cmd, [NSNumber numberWithBool:value]);
}
static double getDoubleProperty(MYDynamicObject *self, SEL _cmd) {
id number = getIdProperty(self,_cmd);
return number ?[number doubleValue] :0.0;
}
static void setDoubleProperty(MYDynamicObject *self, SEL _cmd, double value) {
setIdProperty(self, _cmd, [NSNumber numberWithDouble:value]);
}
static float getFloatProperty(MYDynamicObject *self, SEL _cmd) {
id number = getIdProperty(self,_cmd);
return number ?[number floatValue] :0.0;
}
static void setFloatProperty(MYDynamicObject *self, SEL _cmd, float value) {
setIdProperty(self, _cmd, [NSNumber numberWithFloat:value]);
}
#endif // USE_BLOCKS
#pragma mark - PROPERTY INTROSPECTION:
+ (NSSet*) propertyNames {
static NSMutableDictionary* classToNames;
if (!classToNames)
classToNames = [[NSMutableDictionary alloc] init];
if (self == [MYDynamicObject class])
return [NSSet set];
NSSet* cachedPropertyNames = [classToNames objectForKey:self];
if (cachedPropertyNames)
return cachedPropertyNames;
NSMutableSet* propertyNames = [NSMutableSet set];
objc_property_t* propertiesExcludingSuperclass = class_copyPropertyList(self, NULL);
if (propertiesExcludingSuperclass) {
objc_property_t* propertyPtr = propertiesExcludingSuperclass;
while (*propertyPtr)
[propertyNames addObject:[NSString stringWithUTF8String:property_getName(*propertyPtr++)]];
free(propertiesExcludingSuperclass);
}
[propertyNames unionSet:[[self superclass] propertyNames]];
[classToNames setObject: propertyNames forKey: (id)self];
return propertyNames;
}
// Look up the encoded type of a property, and whether it's settable or readonly
static const char* MYGetPropertyType(objc_property_t property, BOOL *outIsSettable) {
*outIsSettable = YES;
const char *result = "@";
// Copy property attributes into a writeable buffer:
const char *attributes = property_getAttributes(property);
char buffer[1 + strlen(attributes)];
strcpy(buffer, attributes);
// Scan the comma-delimited sections of the string:
char *state = buffer, *attribute;
while ((attribute = strsep(&state, ",")) != NULL) {
switch (attribute[0]) {
case 'T': // Property type in @encode format
result = (const char *)[[NSData dataWithBytes: (attribute + 1)
length: strlen(attribute)] bytes];
break;
case 'R': // Read-only indicator
*outIsSettable = NO;
break;
}
}
return result;
}
// Look up a class's property by name, and find its type and which class declared it
BOOL MYGetPropertyInfo(Class cls,
NSString *propertyName,
BOOL setter,
Class *declaredInClass,
const char* *propertyType) {
// Find the property declaration:
const char *name = [propertyName UTF8String];
objc_property_t property = class_getProperty(cls, name);
if (!property) {
if (![propertyName hasPrefix: @"primitive"]) { // Ignore "primitiveXXX" KVC accessors
LogTo(Model, @"%@ has no dynamic property named '%@' -- failure likely",
cls, propertyName);
}
*propertyType = NULL;
return NO;
}
// Find the class that introduced this property, as cls may have just inherited it:
do {
*declaredInClass = cls;
cls = class_getSuperclass(cls);
} while (class_getProperty(cls, name) == property);
// Get the property's type:
BOOL isSettable;
*propertyType = MYGetPropertyType(property, &isSettable);
if (setter && !isSettable) {
// Asked for a setter, but property is readonly:
*propertyType = NULL;
return NO;
}
return YES;
}
// subroutine for MY___FromType. Invokes callback first with a module-qualified name (if any),
// then if that returns nil, with the base name. Necessary because the class name in the metadata
// doesn't include the class's module, so we have to guess it. (rdar://21368142)
static id lookUp(const char* baseName, Class relativeToClass, id (^callback)(const char*)) {
if (relativeToClass && !strchr(baseName, '.')) {
const char* relativeName = class_getName(relativeToClass);
const char* dot = strchr(relativeName, '.');
if (dot) {
// relativeToClass is in a module, so first look for baseName in that module:
int moduleLen = (int)(dot - relativeName);
char fullName[moduleLen + strlen(baseName) + 2];
sprintf(fullName, "%.*s.%s", moduleLen, relativeName, baseName);
id result = callback(fullName);
if (result)
return result;
// ...if not found in module, try again in without a module...
}
}
return callback(baseName);
}
Class MYClassFromType(const char* propertyType, Class relativeToClass) {
size_t len = strlen(propertyType);
if (propertyType[0] != _C_ID)
return NULL;
if (len == 1)
return [NSObject class]; // Not quite right, but there's no class representing "id"
if (len < 4 || propertyType[1] != '"' || propertyType[len-1] != '"') {
Warn(@"MYDynamicObject: Unknown type encoding: %s", propertyType);
return NULL;
}
char className[len - 2];
strlcpy(className, propertyType + 2, len - 2);
char* bracket = strchr(className, '<');
if (bracket) {
if (bracket == className)
return Nil; // It's a pure protocol name
*bracket = '\0'; // Strip any trailing protocol name(s)
}
return lookUp(className, relativeToClass, ^(const char* name) {
return objc_getClass(name);
});
}
Protocol* MYProtocolFromType(const char* propertyType, Class relativeToClass) {
size_t len = strlen(propertyType);
if (propertyType[0] != _C_ID || propertyType[1] != '"' || propertyType[len-1] != '"'
|| propertyType[2] != '<' || propertyType[len-2] != '>')
return NULL;
char protocolName[len - 4];
strlcpy(protocolName, propertyType + 3, len - 4);
return lookUp(protocolName, relativeToClass, ^(const char* name) {
return objc_getProtocol(name);
});
}
+ (Class) classOfProperty: (NSString*)propertyName {
Class declaredInClass;
const char* propertyType;
if (!MYGetPropertyInfo(self, propertyName, NO, &declaredInClass, &propertyType))
return Nil;
return MYClassFromType(propertyType, self);
}
+ (IMP) impForGetterOfProperty: (NSString*)property ofClass: (Class)propertyClass {
#if USE_BLOCKS
return imp_implementationWithBlock(^id(MYDynamicObject* receiver) {
return [receiver getValueOfProperty: property];
});
#else
return (IMP)getIdProperty;
#endif
}
+ (IMP) impForSetterOfProperty: (NSString*)property ofClass: (Class)propertyClass {
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, id value) {
setIdProperty(receiver, property, value);
});
#else
return (IMP)setIdProperty;
#endif
}
+ (IMP) impForGetterOfProperty: (NSString*)property ofProtocol: (Protocol*)propertyProtocol {
#if USE_BLOCKS
return imp_implementationWithBlock(^id(MYDynamicObject* receiver) {
return [receiver getValueOfProperty: property];
});
#else
return (IMP)getIdProperty;
#endif
}
+ (IMP) impForSetterOfProperty: (NSString*)property ofProtocol: (Protocol*)propertyProtocol {
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, id value) {
setIdProperty(receiver, property, value);
});
#else
return (IMP)setIdProperty;
#endif
}
+ (IMP) impForGetterOfProperty: (NSString*)property ofType: (const char*)propertyType {
switch (propertyType[0]) {
case _C_ID: {
Class klass = MYClassFromType(propertyType, self);
if (klass)
return [self impForGetterOfProperty: property ofClass: klass];
Protocol* proto = MYProtocolFromType(propertyType, self);
if (proto)
return [self impForGetterOfProperty: property ofProtocol: proto];
Warn(@"MYDynamicObject: %@.%@ has type %s which is not a known class or protocol",
self, property, propertyType);
return NULL;
}
case _C_INT:
case _C_SHT:
case _C_USHT:
case _C_CHR:
case _C_UCHR:
#if USE_BLOCKS
return imp_implementationWithBlock(^int(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] intValue];
});
#else
return (IMP)getIntProperty;
#endif
case _C_UINT:
#if USE_BLOCKS
return imp_implementationWithBlock(^unsigned int(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] unsignedIntValue];
});
#else
return (IMP)getUnsignedIntProperty;
#endif
case _C_LNG:
#if USE_BLOCKS
return imp_implementationWithBlock(^long(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] longValue];
});
#else
return (IMP)getLongProperty;
#endif
case _C_ULNG:
#if USE_BLOCKS
return imp_implementationWithBlock(^unsigned long(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] unsignedLongValue];
});
#else
return (IMP)getUnsignedLongProperty;
#endif
case _C_LNG_LNG:
#if USE_BLOCKS
return imp_implementationWithBlock(^long long(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] longLongValue];
});
#else
return (IMP)getLongLongProperty;
#endif
case _C_ULNG_LNG:
#if USE_BLOCKS
return imp_implementationWithBlock(^unsigned long long(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] unsignedLongLongValue];
});
#else
return (IMP)getUnsignedLongLongProperty;
#endif
case _C_BOOL:
#if USE_BLOCKS
return imp_implementationWithBlock(^bool(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] boolValue];
});
#else
return (IMP)getBoolProperty;
#endif
case _C_FLT:
#if USE_BLOCKS
return imp_implementationWithBlock(^float(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] floatValue];
});
#else
return (IMP)getFloatProperty;
#endif
case _C_DBL:
#if USE_BLOCKS
return imp_implementationWithBlock(^double(MYDynamicObject* receiver) {
return [[receiver getValueOfProperty: property] doubleValue];
});
#else
return (IMP)getDoubleProperty;
#endif
default:
return NULL;
}
}
+ (IMP) impForSetterOfProperty: (NSString*)property ofType: (const char*)propertyType {
switch (propertyType[0]) {
case _C_ID: {
Class klass = MYClassFromType(propertyType, self);
if (klass)
return [self impForSetterOfProperty: property ofClass: klass];
Protocol* proto = MYProtocolFromType(propertyType, self);
if (proto)
return [self impForSetterOfProperty: property ofProtocol: proto];
Warn(@"MYDynamicObject: %@.%@ has type %s which is not a known class or protocol",
self, property, propertyType);
return NULL;
}
case _C_INT:
case _C_SHT:
case _C_USHT:
case _C_CHR: // Note that "BOOL" is a typedef so it compiles to 'char'
case _C_UCHR:
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, int value) {
setIdProperty(receiver, property, [NSNumber numberWithInt: value]);
});
#else
return (IMP)setIntProperty;
#endif
case _C_UINT:
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, unsigned int value) {
setIdProperty(receiver, property, [NSNumber numberWithUnsignedInt: value]);
});
#else
return (IMP)setUnsignedIntProperty;
#endif
case _C_LNG:
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, long value) {
setIdProperty(receiver, property, [NSNumber numberWithLong: value]);
});
#else
return (IMP)setLongProperty;
#endif
case _C_ULNG:
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, unsigned long value) {
setIdProperty(receiver, property, [NSNumber numberWithUnsignedLong: value]);
});
#else
return (IMP)setUnsignedLongProperty;
#endif
case _C_LNG_LNG:
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, long long value) {
setIdProperty(receiver, property, [NSNumber numberWithLongLong: value]);
});
#else
return (IMP)setLongLongProperty;
#endif
case _C_ULNG_LNG:
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, unsigned long long value) {
setIdProperty(receiver, property, [NSNumber numberWithUnsignedLongLong: value]);
});
#else
return (IMP)setUnsignedLongLongProperty;
#endif
case _C_BOOL: // This is the true native C99/C++ "bool" type
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, bool value) {
setIdProperty(receiver, property, [NSNumber numberWithBool: value]);
});
#else
return (IMP)setBoolProperty;
#endif
case _C_FLT:
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, float value) {
setIdProperty(receiver, property, [NSNumber numberWithFloat: value]);
});
#else
return (IMP)setFloatProperty;
#endif
case _C_DBL:
#if USE_BLOCKS
return imp_implementationWithBlock(^(MYDynamicObject* receiver, double value) {
setIdProperty(receiver, property, [NSNumber numberWithDouble: value]);
});
#else
return (IMP)setDoubleProperty;
#endif
default:
return NULL;
}
}
// The Objective-C runtime calls this method when it's asked about a method that isn't natively
// implemented by this class. The implementation should either call class_addMethod and return YES,
// or return NO.
+ (BOOL)resolveInstanceMethod:(SEL)sel {
const char *name = sel_getName(sel);
NSString* key;
Class declaredInClass;
const char *propertyType = NULL;
char signature[5];
IMP accessor = NULL;
if (isSetter(name)) {
// choose an appropriately typed generic setter function.
for (int upperCase=NO; upperCase<=YES; upperCase++) {
key = setterKey(sel, (BOOL)upperCase);
if (MYGetPropertyInfo(self, key, YES, &declaredInClass, &propertyType)) {
strcpy(signature, "v@: ");
signature[3] = propertyType[0];
accessor = [self impForSetterOfProperty: key ofType: propertyType];
break;
}
}
} else if (isGetter(name)) {
// choose an appropriately typed getter function.
key = getterKey(sel);
if (MYGetPropertyInfo(self, key, NO, &declaredInClass, &propertyType)) {
strcpy(signature, " @:");
signature[0] = propertyType[0];
accessor = [self impForGetterOfProperty: key ofType: propertyType];
}
} else {
// Not a getter or setter name.
return NO;
}
if (accessor) {
LogVerbose(Model, @"Creating dynamic accessor method -[%@ %s]", declaredInClass, name);
class_addMethod(declaredInClass, sel, accessor, signature);
return YES;
}
if (propertyType) {
Warn(@"Dynamic property %@.%@ has type '%s' unsupported by %@",
self, key, propertyType, self);
}
return NO;
}
@end