RQReflection.m 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. //
  2. // RQReflection.m
  3. // RQCommon
  4. //
  5. // Created by 张嵘 on 2018/11/16.
  6. // Copyright © 2018 张嵘. All rights reserved.
  7. //
  8. #import "RQReflection.h"
  9. #import <objc/runtime.h>
  10. SEL RQSelectorWithKeyPattern(NSString *key, const char *suffix) {
  11. NSUInteger keyLength = [key maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  12. NSUInteger suffixLength = strlen(suffix);
  13. char selector[keyLength + suffixLength + 1];
  14. BOOL success = [key getBytes:selector maxLength:keyLength usedLength:&keyLength encoding:NSUTF8StringEncoding options:0 range:NSMakeRange(0, key.length) remainingRange:NULL];
  15. if (!success) return NULL;
  16. memcpy(selector + keyLength, suffix, suffixLength);
  17. selector[keyLength + suffixLength] = '\0';
  18. return sel_registerName(selector);
  19. }
  20. SEL RQSelectorWithCapitalizedKeyPattern(const char *prefix, NSString *key, const char *suffix) {
  21. NSUInteger prefixLength = strlen(prefix);
  22. NSUInteger suffixLength = strlen(suffix);
  23. NSString *initial = [key substringToIndex:1].uppercaseString;
  24. NSUInteger initialLength = [initial maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  25. NSString *rest = [key substringFromIndex:1];
  26. NSUInteger restLength = [rest maximumLengthOfBytesUsingEncoding:NSUTF8StringEncoding];
  27. char selector[prefixLength + initialLength + restLength + suffixLength + 1];
  28. memcpy(selector, prefix, prefixLength);
  29. BOOL success = [initial getBytes:selector + prefixLength maxLength:initialLength usedLength:&initialLength encoding:NSUTF8StringEncoding options:0 range:NSMakeRange(0, initial.length) remainingRange:NULL];
  30. if (!success) return NULL;
  31. success = [rest getBytes:selector + prefixLength + initialLength maxLength:restLength usedLength:&restLength encoding:NSUTF8StringEncoding options:0 range:NSMakeRange(0, rest.length) remainingRange:NULL];
  32. if (!success) return NULL;
  33. memcpy(selector + prefixLength + initialLength + restLength, suffix, suffixLength);
  34. selector[prefixLength + initialLength + restLength + suffixLength] = '\0';
  35. return sel_registerName(selector);
  36. }