NSObject+OCMAdditions.m 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2009-2015 Erik Doernenburg and contributors
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  5. * not use these files except in compliance with the License. You may obtain
  6. * a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. * License for the specific language governing permissions and limitations
  14. * under the License.
  15. */
  16. #import "NSObject+OCMAdditions.h"
  17. #import "NSMethodSignature+OCMAdditions.h"
  18. #import <objc/runtime.h>
  19. @implementation NSObject(OCMAdditions)
  20. + (IMP)instanceMethodForwarderForSelector:(SEL)aSelector
  21. {
  22. // use sel_registerName() and not @selector to avoid warning
  23. SEL selectorWithNoImplementation = sel_registerName("methodWhichMustNotExist::::");
  24. #ifndef __arm64__
  25. static NSMutableDictionary *_OCMReturnTypeCache;
  26. if(_OCMReturnTypeCache == nil)
  27. _OCMReturnTypeCache = [[NSMutableDictionary alloc] init];
  28. BOOL needsStructureReturn;
  29. void *rawCacheKey[2] = { (void *)self, aSelector };
  30. NSData *cacheKey = [NSData dataWithBytes:rawCacheKey length:sizeof(rawCacheKey)];
  31. NSNumber *cachedValue = [_OCMReturnTypeCache objectForKey:cacheKey];
  32. if(cachedValue == nil)
  33. {
  34. NSMethodSignature *sig = [self instanceMethodSignatureForSelector:aSelector];
  35. needsStructureReturn = [sig usesSpecialStructureReturn];
  36. [_OCMReturnTypeCache setObject:@(needsStructureReturn) forKey:cacheKey];
  37. }
  38. else
  39. {
  40. needsStructureReturn = [cachedValue boolValue];
  41. }
  42. if(needsStructureReturn)
  43. return class_getMethodImplementation_stret([NSObject class], selectorWithNoImplementation);
  44. #endif
  45. return class_getMethodImplementation([NSObject class], selectorWithNoImplementation);
  46. }
  47. + (void)enumerateMethodsInClass:(Class)aClass usingBlock:(void (^)(Class cls, SEL sel))aBlock
  48. {
  49. for(Class cls = aClass; cls != nil; cls = class_getSuperclass(cls))
  50. {
  51. Method *methodList = class_copyMethodList(cls, NULL);
  52. if(methodList == NULL)
  53. continue;
  54. for(Method *mPtr = methodList; *mPtr != NULL; mPtr++)
  55. {
  56. SEL sel = method_getName(*mPtr);
  57. aBlock(cls, sel);
  58. }
  59. free(methodList);
  60. }
  61. }
  62. @end