FLEXRuntimeUtility.m 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698
  1. //
  2. // FLEXRuntimeUtility.m
  3. // Flipboard
  4. //
  5. // Created by Ryan Olson on 6/8/14.
  6. // Copyright (c) 2014 Flipboard. All rights reserved.
  7. //
  8. #import <UIKit/UIKit.h>
  9. #import "FLEXRuntimeUtility.h"
  10. // See https://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtPropertyIntrospection.html#//apple_ref/doc/uid/TP40008048-CH101-SW6
  11. NSString *const kFLEXUtilityAttributeTypeEncoding = @"T";
  12. NSString *const kFLEXUtilityAttributeBackingIvar = @"V";
  13. NSString *const kFLEXUtilityAttributeReadOnly = @"R";
  14. NSString *const kFLEXUtilityAttributeCopy = @"C";
  15. NSString *const kFLEXUtilityAttributeRetain = @"&";
  16. NSString *const kFLEXUtilityAttributeNonAtomic = @"N";
  17. NSString *const kFLEXUtilityAttributeCustomGetter = @"G";
  18. NSString *const kFLEXUtilityAttributeCustomSetter = @"S";
  19. NSString *const kFLEXUtilityAttributeDynamic = @"D";
  20. NSString *const kFLEXUtilityAttributeWeak = @"W";
  21. NSString *const kFLEXUtilityAttributeGarbageCollectable = @"P";
  22. NSString *const kFLEXUtilityAttributeOldStyleTypeEncoding = @"t";
  23. static NSString *const FLEXRuntimeUtilityErrorDomain = @"FLEXRuntimeUtilityErrorDomain";
  24. typedef NS_ENUM(NSInteger, FLEXRuntimeUtilityErrorCode) {
  25. FLEXRuntimeUtilityErrorCodeDoesNotRecognizeSelector = 0,
  26. FLEXRuntimeUtilityErrorCodeInvocationFailed = 1,
  27. FLEXRuntimeUtilityErrorCodeArgumentTypeMismatch = 2
  28. };
  29. // Arguments 0 and 1 are self and _cmd always
  30. const unsigned int kFLEXNumberOfImplicitArgs = 2;
  31. @implementation FLEXRuntimeUtility
  32. #pragma mark - Property Helpers (Public)
  33. + (NSString *)prettyNameForProperty:(objc_property_t)property
  34. {
  35. NSString *name = @(property_getName(property));
  36. NSString *encoding = [self typeEncodingForProperty:property];
  37. NSString *readableType = [self readableTypeForEncoding:encoding];
  38. return [self appendName:name toType:readableType];
  39. }
  40. + (NSString *)typeEncodingForProperty:(objc_property_t)property
  41. {
  42. NSDictionary *attributesDictionary = [self attributesDictionaryForProperty:property];
  43. return [attributesDictionary objectForKey:kFLEXUtilityAttributeTypeEncoding];
  44. }
  45. + (BOOL)isReadonlyProperty:(objc_property_t)property
  46. {
  47. return [[self attributesDictionaryForProperty:property] objectForKey:kFLEXUtilityAttributeReadOnly] != nil;
  48. }
  49. + (SEL)setterSelectorForProperty:(objc_property_t)property
  50. {
  51. SEL setterSelector = NULL;
  52. NSString *setterSelectorString = [[self attributesDictionaryForProperty:property] objectForKey:kFLEXUtilityAttributeCustomSetter];
  53. if (!setterSelectorString) {
  54. NSString *propertyName = @(property_getName(property));
  55. setterSelectorString = [NSString stringWithFormat:@"set%@%@:", [[propertyName substringToIndex:1] uppercaseString], [propertyName substringFromIndex:1]];
  56. }
  57. if (setterSelectorString) {
  58. setterSelector = NSSelectorFromString(setterSelectorString);
  59. }
  60. return setterSelector;
  61. }
  62. + (NSString *)fullDescriptionForProperty:(objc_property_t)property
  63. {
  64. NSDictionary *attributesDictionary = [self attributesDictionaryForProperty:property];
  65. NSMutableArray *attributesStrings = [NSMutableArray array];
  66. // Atomicity
  67. if ([attributesDictionary objectForKey:kFLEXUtilityAttributeNonAtomic]) {
  68. [attributesStrings addObject:@"nonatomic"];
  69. } else {
  70. [attributesStrings addObject:@"atomic"];
  71. }
  72. // Storage
  73. if ([attributesDictionary objectForKey:kFLEXUtilityAttributeRetain]) {
  74. [attributesStrings addObject:@"strong"];
  75. } else if ([attributesDictionary objectForKey:kFLEXUtilityAttributeCopy]) {
  76. [attributesStrings addObject:@"copy"];
  77. } else if ([attributesDictionary objectForKey:kFLEXUtilityAttributeWeak]) {
  78. [attributesStrings addObject:@"weak"];
  79. } else {
  80. [attributesStrings addObject:@"assign"];
  81. }
  82. // Mutability
  83. if ([attributesDictionary objectForKey:kFLEXUtilityAttributeReadOnly]) {
  84. [attributesStrings addObject:@"readonly"];
  85. } else {
  86. [attributesStrings addObject:@"readwrite"];
  87. }
  88. // Custom getter/setter
  89. NSString *customGetter = [attributesDictionary objectForKey:kFLEXUtilityAttributeCustomGetter];
  90. NSString *customSetter = [attributesDictionary objectForKey:kFLEXUtilityAttributeCustomSetter];
  91. if (customGetter) {
  92. [attributesStrings addObject:[NSString stringWithFormat:@"getter=%@", customGetter]];
  93. }
  94. if (customSetter) {
  95. [attributesStrings addObject:[NSString stringWithFormat:@"setter=%@", customSetter]];
  96. }
  97. NSString *attributesString = [attributesStrings componentsJoinedByString:@", "];
  98. NSString *shortName = [self prettyNameForProperty:property];
  99. return [NSString stringWithFormat:@"@property (%@) %@", attributesString, shortName];
  100. }
  101. + (id)valueForProperty:(objc_property_t)property onObject:(id)object
  102. {
  103. NSString *customGetterString = nil;
  104. char *customGetterName = property_copyAttributeValue(property, "G");
  105. if (customGetterName) {
  106. customGetterString = @(customGetterName);
  107. free(customGetterName);
  108. }
  109. SEL getterSelector;
  110. if ([customGetterString length] > 0) {
  111. getterSelector = NSSelectorFromString(customGetterString);
  112. } else {
  113. NSString *propertyName = @(property_getName(property));
  114. getterSelector = NSSelectorFromString(propertyName);
  115. }
  116. return [self performSelector:getterSelector onObject:object withArguments:nil error:NULL];
  117. }
  118. + (NSString *)descriptionForIvarOrPropertyValue:(id)value
  119. {
  120. NSString *description = nil;
  121. // Special case BOOL for better readability.
  122. if ([value isKindOfClass:[NSValue class]]) {
  123. const char *type = [value objCType];
  124. if (strcmp(type, @encode(BOOL)) == 0) {
  125. BOOL boolValue = NO;
  126. [value getValue:&boolValue];
  127. description = boolValue ? @"YES" : @"NO";
  128. }
  129. }
  130. if (!description) {
  131. // Single line display - replace newlines and tabs with spaces.
  132. description = [[value description] stringByReplacingOccurrencesOfString:@"\n" withString:@" "];
  133. description = [description stringByReplacingOccurrencesOfString:@"\t" withString:@" "];
  134. }
  135. if (!description) {
  136. description = @"nil";
  137. }
  138. return description;
  139. }
  140. + (void)tryAddPropertyWithName:(const char *)name attributes:(NSDictionary *)attributePairs toClass:(__unsafe_unretained Class)theClass
  141. {
  142. objc_property_t property = class_getProperty(theClass, name);
  143. if (!property) {
  144. unsigned int totalAttributesCount = (unsigned int)[attributePairs count];
  145. objc_property_attribute_t *attributes = malloc(sizeof(objc_property_attribute_t) * totalAttributesCount);
  146. if (attributes) {
  147. unsigned int attributeIndex = 0;
  148. for (NSString *attributeName in [attributePairs allKeys]) {
  149. objc_property_attribute_t attribute;
  150. attribute.name = [attributeName UTF8String];
  151. attribute.value = [[attributePairs objectForKey:attributeName] UTF8String];
  152. attributes[attributeIndex++] = attribute;
  153. }
  154. class_addProperty(theClass, name, attributes, totalAttributesCount);
  155. free(attributes);
  156. }
  157. }
  158. }
  159. #pragma mark - Ivar Helpers (Public)
  160. + (NSString *)prettyNameForIvar:(Ivar)ivar
  161. {
  162. const char *nameCString = ivar_getName(ivar);
  163. NSString *name = nameCString ? @(nameCString) : nil;
  164. const char *encodingCString = ivar_getTypeEncoding(ivar);
  165. NSString *encoding = encodingCString ? @(encodingCString) : nil;
  166. NSString *readableType = [self readableTypeForEncoding:encoding];
  167. return [self appendName:name toType:readableType];
  168. }
  169. + (id)valueForIvar:(Ivar)ivar onObject:(id)object
  170. {
  171. id value = nil;
  172. const char *type = ivar_getTypeEncoding(ivar);
  173. if (type[0] == @encode(id)[0] || type[0] == @encode(Class)[0]) {
  174. value = object_getIvar(object, ivar);
  175. } else {
  176. ptrdiff_t offset = ivar_getOffset(ivar);
  177. void *pointer = (__bridge void *)object + offset;
  178. value = [self valueForPrimitivePointer:pointer objCType:type];
  179. }
  180. return value;
  181. }
  182. + (void)setValue:(id)value forIvar:(Ivar)ivar onObject:(id)object
  183. {
  184. const char *typeEncodingCString = ivar_getTypeEncoding(ivar);
  185. if (typeEncodingCString[0] == '@') {
  186. object_setIvar(object, ivar, value);
  187. } else if ([value isKindOfClass:[NSValue class]]) {
  188. // Primitive - unbox the NSValue.
  189. NSValue *valueValue = (NSValue *)value;
  190. // Make sure that the box contained the correct type.
  191. NSAssert(strcmp([valueValue objCType], typeEncodingCString) == 0, @"Type encoding mismatch (value: %s; ivar: %s) in setting ivar named: %s on object: %@", [valueValue objCType], typeEncodingCString, ivar_getName(ivar), object);
  192. NSUInteger bufferSize = 0;
  193. @try {
  194. // NSGetSizeAndAlignment barfs on type encoding for bitfields.
  195. NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL);
  196. } @catch (NSException *exception) { }
  197. if (bufferSize > 0) {
  198. void *buffer = calloc(bufferSize, 1);
  199. [valueValue getValue:buffer];
  200. ptrdiff_t offset = ivar_getOffset(ivar);
  201. void *pointer = (__bridge void *)object + offset;
  202. memcpy(pointer, buffer, bufferSize);
  203. free(buffer);
  204. }
  205. }
  206. }
  207. #pragma mark - Method Helpers (Public)
  208. + (NSString *)prettyNameForMethod:(Method)method isClassMethod:(BOOL)isClassMethod
  209. {
  210. NSString *selectorName = NSStringFromSelector(method_getName(method));
  211. NSString *methodTypeString = isClassMethod ? @"+" : @"-";
  212. char *returnType = method_copyReturnType(method);
  213. NSString *readableReturnType = [self readableTypeForEncoding:@(returnType)];
  214. free(returnType);
  215. NSString *prettyName = [NSString stringWithFormat:@"%@ (%@)", methodTypeString, readableReturnType];
  216. NSArray *components = [self prettyArgumentComponentsForMethod:method];
  217. if ([components count] > 0) {
  218. prettyName = [prettyName stringByAppendingString:[components componentsJoinedByString:@" "]];
  219. } else {
  220. prettyName = [prettyName stringByAppendingString:selectorName];
  221. }
  222. return prettyName;
  223. }
  224. + (NSArray *)prettyArgumentComponentsForMethod:(Method)method
  225. {
  226. NSMutableArray *components = [NSMutableArray array];
  227. NSString *selectorName = NSStringFromSelector(method_getName(method));
  228. NSArray *selectorComponents = [selectorName componentsSeparatedByString:@":"];
  229. unsigned int numberOfArguments = method_getNumberOfArguments(method);
  230. for (unsigned int argIndex = kFLEXNumberOfImplicitArgs; argIndex < numberOfArguments; argIndex++) {
  231. char *argType = method_copyArgumentType(method, argIndex);
  232. NSString *readableArgType = [self readableTypeForEncoding:@(argType)];
  233. free(argType);
  234. NSString *prettyComponent = [NSString stringWithFormat:@"%@:(%@) ", [selectorComponents objectAtIndex:argIndex - kFLEXNumberOfImplicitArgs], readableArgType];
  235. [components addObject:prettyComponent];
  236. }
  237. return components;
  238. }
  239. #pragma mark - Method Calling/Field Editing (Public)
  240. + (id)performSelector:(SEL)selector onObject:(id)object withArguments:(NSArray *)arguments error:(NSError * __autoreleasing *)error
  241. {
  242. // Bail if the object won't respond to this selector.
  243. if (![object respondsToSelector:selector]) {
  244. if (error) {
  245. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"%@ does not respond to the selector %@", object, NSStringFromSelector(selector)]};
  246. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeDoesNotRecognizeSelector userInfo:userInfo];
  247. }
  248. return nil;
  249. }
  250. // Build the invocation
  251. NSMethodSignature *methodSignature = [object methodSignatureForSelector:selector];
  252. NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:methodSignature];
  253. [invocation setSelector:selector];
  254. [invocation setTarget:object];
  255. [invocation retainArguments];
  256. // Always self and _cmd
  257. NSUInteger numberOfArguments = [methodSignature numberOfArguments];
  258. for (NSUInteger argumentIndex = kFLEXNumberOfImplicitArgs; argumentIndex < numberOfArguments; argumentIndex++) {
  259. NSUInteger argumentsArrayIndex = argumentIndex - kFLEXNumberOfImplicitArgs;
  260. id argumentObject = [arguments count] > argumentsArrayIndex ? [arguments objectAtIndex:argumentsArrayIndex] : nil;
  261. // NSNull in the arguments array can be passed as a placeholder to indicate nil. We only need to set the argument if it will be non-nil.
  262. if (argumentObject && ![argumentObject isKindOfClass:[NSNull class]]) {
  263. const char *typeEncodingCString = [methodSignature getArgumentTypeAtIndex:argumentIndex];
  264. if (typeEncodingCString[0] == @encode(id)[0] || typeEncodingCString[0] == @encode(Class)[0] || [self isTollFreeBridgedValue:argumentObject forCFType:typeEncodingCString]) {
  265. // Object
  266. [invocation setArgument:&argumentObject atIndex:argumentIndex];
  267. } else if (strcmp(typeEncodingCString, @encode(CGColorRef)) == 0 && [argumentObject isKindOfClass:[UIColor class]]) {
  268. // Bridging UIColor to CGColorRef
  269. CGColorRef colorRef = [argumentObject CGColor];
  270. [invocation setArgument:&colorRef atIndex:argumentIndex];
  271. } else if ([argumentObject isKindOfClass:[NSValue class]]) {
  272. // Primitive boxed in NSValue
  273. NSValue *argumentValue = (NSValue *)argumentObject;
  274. // Ensure that the type encoding on the NSValue matches the type encoding of the argument in the method signature
  275. if (strcmp([argumentValue objCType], typeEncodingCString) != 0) {
  276. if (error) {
  277. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Type encoding mismatch for agrument at index %lu. Value type: %s; Method argument type: %s.", (unsigned long)argumentsArrayIndex, [argumentValue objCType], typeEncodingCString]};
  278. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeArgumentTypeMismatch userInfo:userInfo];
  279. }
  280. return nil;
  281. }
  282. NSUInteger bufferSize = 0;
  283. @try {
  284. // NSGetSizeAndAlignment barfs on type encoding for bitfields.
  285. NSGetSizeAndAlignment(typeEncodingCString, &bufferSize, NULL);
  286. } @catch (NSException *exception) { }
  287. if (bufferSize > 0) {
  288. void *buffer = calloc(bufferSize, 1);
  289. [argumentValue getValue:buffer];
  290. [invocation setArgument:buffer atIndex:argumentIndex];
  291. free(buffer);
  292. }
  293. }
  294. }
  295. }
  296. // Try to invoke the invocation but guard against an exception being thrown.
  297. BOOL successfullyInvoked = NO;
  298. @try {
  299. // Some methods are not fit to be called...
  300. // Looking at you -[UIResponder(UITextInputAdditions) _caretRect]
  301. [invocation invoke];
  302. successfullyInvoked = YES;
  303. } @catch (NSException *exception) {
  304. // Bummer...
  305. if (error) {
  306. NSDictionary *userInfo = @{ NSLocalizedDescriptionKey : [NSString stringWithFormat:@"Exception thrown while performing selector %@ on object %@", NSStringFromSelector(selector), object]};
  307. *error = [NSError errorWithDomain:FLEXRuntimeUtilityErrorDomain code:FLEXRuntimeUtilityErrorCodeInvocationFailed userInfo:userInfo];
  308. }
  309. }
  310. // Retreive the return value and box if necessary.
  311. id returnObject = nil;
  312. if (successfullyInvoked) {
  313. const char *returnType = [methodSignature methodReturnType];
  314. if (returnType[0] == @encode(id)[0] || returnType[0] == @encode(Class)[0]) {
  315. __unsafe_unretained id objectReturnedFromMethod = nil;
  316. [invocation getReturnValue:&objectReturnedFromMethod];
  317. returnObject = objectReturnedFromMethod;
  318. } else if (returnType[0] != @encode(void)[0]) {
  319. void *returnValue = malloc([methodSignature methodReturnLength]);
  320. if (returnValue) {
  321. [invocation getReturnValue:returnValue];
  322. returnObject = [self valueForPrimitivePointer:returnValue objCType:returnType];
  323. free(returnValue);
  324. }
  325. }
  326. }
  327. return returnObject;
  328. }
  329. + (BOOL)isTollFreeBridgedValue:(id)value forCFType:(const char *)typeEncoding
  330. {
  331. // See https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/Toll-FreeBridgin/Toll-FreeBridgin.html
  332. #define CASE(cftype, foundationClass) \
  333. if(strcmp(typeEncoding, @encode(cftype)) == 0) { \
  334. return [value isKindOfClass:[foundationClass class]]; \
  335. }
  336. CASE(CFArrayRef, NSArray);
  337. CASE(CFAttributedStringRef, NSAttributedString);
  338. CASE(CFCalendarRef, NSCalendar);
  339. CASE(CFCharacterSetRef, NSCharacterSet);
  340. CASE(CFDataRef, NSData);
  341. CASE(CFDateRef, NSDate);
  342. CASE(CFDictionaryRef, NSDictionary);
  343. CASE(CFErrorRef, NSError);
  344. CASE(CFLocaleRef, NSLocale);
  345. CASE(CFMutableArrayRef, NSMutableArray);
  346. CASE(CFMutableAttributedStringRef, NSMutableAttributedString);
  347. CASE(CFMutableCharacterSetRef, NSMutableCharacterSet);
  348. CASE(CFMutableDataRef, NSMutableData);
  349. CASE(CFMutableDictionaryRef, NSMutableDictionary);
  350. CASE(CFMutableSetRef, NSMutableSet);
  351. CASE(CFMutableStringRef, NSMutableString);
  352. CASE(CFNumberRef, NSNumber);
  353. CASE(CFReadStreamRef, NSInputStream);
  354. CASE(CFRunLoopTimerRef, NSTimer);
  355. CASE(CFSetRef, NSSet);
  356. CASE(CFStringRef, NSString);
  357. CASE(CFTimeZoneRef, NSTimeZone);
  358. CASE(CFURLRef, NSURL);
  359. CASE(CFWriteStreamRef, NSOutputStream);
  360. #undef CASE
  361. return NO;
  362. }
  363. + (NSString *)editableJSONStringForObject:(id)object
  364. {
  365. NSString *editableDescription = nil;
  366. if (object) {
  367. // This is a hack to use JSON serialzation for our editable objects.
  368. // NSJSONSerialization doesn't allow writing fragments - the top level object must be an array or dictionary.
  369. // We always wrap the object inside an array and then strip the outter square braces off the final string.
  370. NSArray *wrappedObject = @[object];
  371. if ([NSJSONSerialization isValidJSONObject:wrappedObject]) {
  372. NSString *wrappedDescription = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:wrappedObject options:0 error:NULL] encoding:NSUTF8StringEncoding];
  373. editableDescription = [wrappedDescription substringWithRange:NSMakeRange(1, [wrappedDescription length] - 2)];
  374. }
  375. }
  376. return editableDescription;
  377. }
  378. + (id)objectValueFromEditableJSONString:(NSString *)string
  379. {
  380. id value = nil;
  381. // nil for empty string/whitespace
  382. if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] length] > 0) {
  383. value = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingAllowFragments error:NULL];
  384. }
  385. return value;
  386. }
  387. + (NSValue *)valueForNumberWithObjCType:(const char *)typeEncoding fromInputString:(NSString *)inputString
  388. {
  389. NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
  390. [formatter setNumberStyle:NSNumberFormatterDecimalStyle];
  391. NSNumber *number = [formatter numberFromString:inputString];
  392. // Make sure we box the number with the correct type encoding so it can be propperly unboxed later via getValue:
  393. NSValue *value = nil;
  394. if (strcmp(typeEncoding, @encode(char)) == 0) {
  395. char primitiveValue = [number charValue];
  396. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  397. } else if (strcmp(typeEncoding, @encode(int)) == 0) {
  398. int primitiveValue = [number intValue];
  399. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  400. } else if (strcmp(typeEncoding, @encode(short)) == 0) {
  401. short primitiveValue = [number shortValue];
  402. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  403. } else if (strcmp(typeEncoding, @encode(long)) == 0) {
  404. long primitiveValue = [number longValue];
  405. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  406. } else if (strcmp(typeEncoding, @encode(long long)) == 0) {
  407. long long primitiveValue = [number longLongValue];
  408. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  409. } else if (strcmp(typeEncoding, @encode(unsigned char)) == 0) {
  410. unsigned char primitiveValue = [number unsignedCharValue];
  411. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  412. } else if (strcmp(typeEncoding, @encode(unsigned int)) == 0) {
  413. unsigned int primitiveValue = [number unsignedIntValue];
  414. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  415. } else if (strcmp(typeEncoding, @encode(unsigned short)) == 0) {
  416. unsigned short primitiveValue = [number unsignedShortValue];
  417. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  418. } else if (strcmp(typeEncoding, @encode(unsigned long)) == 0) {
  419. unsigned long primitiveValue = [number unsignedLongValue];
  420. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  421. } else if (strcmp(typeEncoding, @encode(unsigned long long)) == 0) {
  422. unsigned long long primitiveValue = [number unsignedLongValue];
  423. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  424. } else if (strcmp(typeEncoding, @encode(float)) == 0) {
  425. float primitiveValue = [number floatValue];
  426. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  427. } else if (strcmp(typeEncoding, @encode(double)) == 0) {
  428. double primitiveValue = [number doubleValue];
  429. value = [NSValue value:&primitiveValue withObjCType:typeEncoding];
  430. }
  431. return value;
  432. }
  433. + (void)enumerateTypesInStructEncoding:(const char *)structEncoding usingBlock:(void (^)(NSString *structName, const char *fieldTypeEncoding, NSString *prettyTypeEncoding, NSUInteger fieldIndex, NSUInteger fieldOffset))typeBlock
  434. {
  435. if (structEncoding && structEncoding[0] == '{') {
  436. const char *equals = strchr(structEncoding, '=');
  437. if (equals) {
  438. const char *nameStart = structEncoding + 1;
  439. NSString *structName = [@(structEncoding) substringWithRange:NSMakeRange(nameStart - structEncoding, equals - nameStart)];
  440. NSUInteger fieldAlignment = 0;
  441. NSUInteger structSize = 0;
  442. @try {
  443. // NSGetSizeAndAlignment barfs on type encoding for bitfields.
  444. NSGetSizeAndAlignment(structEncoding, &structSize, &fieldAlignment);
  445. } @catch (NSException *exception) { }
  446. if (structSize > 0) {
  447. NSUInteger runningFieldIndex = 0;
  448. NSUInteger runningFieldOffset = 0;
  449. const char *typeStart = equals + 1;
  450. while (*typeStart != '}') {
  451. NSUInteger fieldSize = 0;
  452. // If the struct type encoding was successfully handled by NSGetSizeAndAlignment above, we *should* be ok with the field here.
  453. const char *nextTypeStart = NSGetSizeAndAlignment(typeStart, &fieldSize, NULL);
  454. NSString *typeEncoding = [@(structEncoding) substringWithRange:NSMakeRange(typeStart - structEncoding, nextTypeStart - typeStart)];
  455. typeBlock(structName, [typeEncoding UTF8String], [self readableTypeForEncoding:typeEncoding], runningFieldIndex, runningFieldOffset);
  456. runningFieldOffset += fieldSize;
  457. // Padding to keep propper alignment. __attribute((packed)) structs will break here.
  458. // The type encoding is no different for packed structs, so it's not clear there's anything we can do for those.
  459. if (runningFieldOffset % fieldAlignment != 0) {
  460. runningFieldOffset += fieldAlignment - runningFieldOffset % fieldAlignment;
  461. }
  462. runningFieldIndex++;
  463. typeStart = nextTypeStart;
  464. }
  465. }
  466. }
  467. }
  468. }
  469. #pragma mark - Internal Helpers
  470. + (NSDictionary *)attributesDictionaryForProperty:(objc_property_t)property
  471. {
  472. NSString *attributes = @(property_getAttributes(property));
  473. // Thanks to MAObjcRuntime for inspiration here.
  474. NSArray *attributePairs = [attributes componentsSeparatedByString:@","];
  475. NSMutableDictionary *attributesDictionary = [NSMutableDictionary dictionaryWithCapacity:[attributePairs count]];
  476. for (NSString *attributePair in attributePairs) {
  477. [attributesDictionary setObject:[attributePair substringFromIndex:1] forKey:[attributePair substringToIndex:1]];
  478. }
  479. return attributesDictionary;
  480. }
  481. + (NSString *)appendName:(NSString *)name toType:(NSString *)type
  482. {
  483. NSString *combined = nil;
  484. if ([type characterAtIndex:[type length] - 1] == '*') {
  485. combined = [type stringByAppendingString:name];
  486. } else {
  487. combined = [type stringByAppendingFormat:@" %@", name];
  488. }
  489. return combined;
  490. }
  491. + (NSString *)readableTypeForEncoding:(NSString *)encodingString
  492. {
  493. if (!encodingString) {
  494. return nil;
  495. }
  496. // See https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/ObjCRuntimeGuide/Articles/ocrtTypeEncodings.html
  497. // class-dump has a much nicer and much more complete implementation for this task, but it is distributed under GPLv2 :/
  498. // See https://github.com/nygard/class-dump/blob/master/Source/CDType.m
  499. // Warning: this method uses multiple middle returns and macros to cut down on boilerplate.
  500. // The use of macros here was inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html
  501. const char *encodingCString = [encodingString UTF8String];
  502. // Objects
  503. if (encodingCString[0] == '@') {
  504. NSString *class = [encodingString substringFromIndex:1];
  505. class = [class stringByReplacingOccurrencesOfString:@"\"" withString:@""];
  506. if ([class length] == 0) {
  507. class = @"id";
  508. } else {
  509. class = [class stringByAppendingString:@" *"];
  510. }
  511. return class;
  512. }
  513. // C Types
  514. #define TRANSLATE(ctype) \
  515. if (strcmp(encodingCString, @encode(ctype)) == 0) { \
  516. return (NSString *)CFSTR(#ctype); \
  517. }
  518. // Order matters here since some of the cocoa types are typedefed to c types.
  519. // We can't recover the exact mapping, but we choose to prefer the cocoa types.
  520. // This is not an exhaustive list, but it covers the most common types
  521. TRANSLATE(CGRect);
  522. TRANSLATE(CGPoint);
  523. TRANSLATE(CGSize);
  524. TRANSLATE(UIEdgeInsets);
  525. TRANSLATE(UIOffset);
  526. TRANSLATE(NSRange);
  527. TRANSLATE(CGAffineTransform);
  528. TRANSLATE(CATransform3D);
  529. TRANSLATE(CGColorRef);
  530. TRANSLATE(CGPathRef);
  531. TRANSLATE(CGContextRef);
  532. TRANSLATE(NSInteger);
  533. TRANSLATE(NSUInteger);
  534. TRANSLATE(CGFloat);
  535. TRANSLATE(BOOL);
  536. TRANSLATE(int);
  537. TRANSLATE(short);
  538. TRANSLATE(long);
  539. TRANSLATE(long long);
  540. TRANSLATE(unsigned char);
  541. TRANSLATE(unsigned int);
  542. TRANSLATE(unsigned short);
  543. TRANSLATE(unsigned long);
  544. TRANSLATE(unsigned long long);
  545. TRANSLATE(float);
  546. TRANSLATE(double);
  547. TRANSLATE(long double);
  548. TRANSLATE(char *);
  549. TRANSLATE(Class);
  550. TRANSLATE(objc_property_t);
  551. TRANSLATE(Ivar);
  552. TRANSLATE(Method);
  553. TRANSLATE(Category);
  554. TRANSLATE(NSZone *);
  555. TRANSLATE(SEL);
  556. TRANSLATE(void);
  557. #undef TRANSLATE
  558. // Qualifier Prefixes
  559. // Do this after the checks above since some of the direct translations (i.e. Method) contain a prefix.
  560. #define RECURSIVE_TRANSLATE(prefix, formatString) \
  561. if (encodingCString[0] == prefix) { \
  562. NSString *recursiveType = [self readableTypeForEncoding:[encodingString substringFromIndex:1]]; \
  563. return [NSString stringWithFormat:formatString, recursiveType]; \
  564. }
  565. // If there's a qualifier prefix on the encoding, translate it and then
  566. // recursively call this method with the rest of the encoding string.
  567. RECURSIVE_TRANSLATE('^', @"%@ *");
  568. RECURSIVE_TRANSLATE('r', @"const %@");
  569. RECURSIVE_TRANSLATE('n', @"in %@");
  570. RECURSIVE_TRANSLATE('N', @"inout %@");
  571. RECURSIVE_TRANSLATE('o', @"out %@");
  572. RECURSIVE_TRANSLATE('O', @"bycopy %@");
  573. RECURSIVE_TRANSLATE('R', @"byref %@");
  574. RECURSIVE_TRANSLATE('V', @"oneway %@");
  575. RECURSIVE_TRANSLATE('b', @"bitfield(%@)");
  576. #undef RECURSIVE_TRANSLATE
  577. // If we couldn't translate, just return the original encoding string
  578. return encodingString;
  579. }
  580. + (NSValue *)valueForPrimitivePointer:(void *)pointer objCType:(const char *)type
  581. {
  582. // CASE marcro inspired by https://www.mikeash.com/pyblog/friday-qa-2013-02-08-lets-build-key-value-coding.html
  583. #define CASE(ctype, selectorpart) \
  584. if(strcmp(type, @encode(ctype)) == 0) { \
  585. return [NSNumber numberWith ## selectorpart: *(ctype *)pointer]; \
  586. }
  587. CASE(BOOL, Bool);
  588. CASE(unsigned char, UnsignedChar);
  589. CASE(short, Short);
  590. CASE(unsigned short, UnsignedShort);
  591. CASE(int, Int);
  592. CASE(unsigned int, UnsignedInt);
  593. CASE(long, Long);
  594. CASE(unsigned long, UnsignedLong);
  595. CASE(long long, LongLong);
  596. CASE(unsigned long long, UnsignedLongLong);
  597. CASE(float, Float);
  598. CASE(double, Double);
  599. #undef CASE
  600. NSValue *value = nil;
  601. @try {
  602. value = [NSValue valueWithBytes:pointer objCType:type];
  603. } @catch (NSException *exception) {
  604. // Certain type encodings are not supported by valueWithBytes:objCType:. Just fail silently if an exception is thrown.
  605. }
  606. return value;
  607. }
  608. @end