FLEXRuntimeUtility.m 29 KB

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