奉上:官方文档地址.
不过官网文档提供的get set 内部查找的方法,比实际上自己测试发现可用的方法要少一些,说明是可能是后期增加了方法,但是没更改文档。

Setter

image.png
image.png

  1. //设值
  2. - (void)cjl_setValue:(nullable id)value forKey:(NSString *)key{
  3. // 1、判断key 是否存在
  4. if (key == nil || key.length == 0) return;
  5. // 2、找setter方法,顺序是:setXXX、_setXXX、 setIsXXX
  6. // key 要大写
  7. NSString *Key = key.capitalizedString;
  8. // key 要大写
  9. NSString *setKey = [NSString stringWithFormat:@"set%@:", Key];
  10. NSString *_setKey = [NSString stringWithFormat:@"_set%@:", Key];
  11. NSString *setIsKey = [NSString stringWithFormat:@"setIs%@:", Key];
  12. if ([self cjl_performSelectorWithMethodName:setKey value:value]) {
  13. NSLog(@"*************%@*************", setKey);
  14. return;
  15. }else if([self cjl_performSelectorWithMethodName:_setKey value:value]){
  16. NSLog(@"*************%@*************", _setKey);
  17. return;
  18. }else if([self cjl_performSelectorWithMethodName:setIsKey value:value]){
  19. NSLog(@"*************%@*************", setIsKey);
  20. return;
  21. }
  22. // 3、判断是否响应`accessInstanceVariablesDirectly`方法,即间接访问实例变量,返回YES,继续下一步设值,如果是NO,则崩溃
  23. if (![self.class accessInstanceVariablesDirectly]) {
  24. @throw [NSException exceptionWithName:@"CJLUnKnownKeyException" reason:[NSString stringWithFormat:@"****[%@ valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.****",self] userInfo:nil];
  25. }
  26. // 4、间接访问变量赋值,顺序为:_key、_isKey、key、isKey
  27. // 4.1 定义一个收集实例变量的可变数组
  28. NSMutableArray *mArray = [self getIvarListName];
  29. // _<key> _is<Key> <key> is<Key>
  30. NSString *_key = [NSString stringWithFormat:@"_%@", key];
  31. NSString *_isKey = [NSString stringWithFormat:@"_is%@", key];
  32. NSString *isKey = [NSString stringWithFormat:@"is%@", key];
  33. if ([mArray containsObject:_key]) {
  34. // 4.2 获取相应的 ivar
  35. Ivar ivar = class_getInstanceVariable([self class], _key.UTF8String);
  36. // 4.3 对相应的 ivar 设置值
  37. object_setIvar(self, ivar, value);
  38. return;
  39. }else if ([mArray containsObject:_isKey]) {
  40. Ivar ivar = class_getInstanceVariable([self class], _isKey.UTF8String);
  41. object_setIvar(self, ivar, value);
  42. return;
  43. }else if ([mArray containsObject:key]) {
  44. Ivar ivar = class_getInstanceVariable([self class], key.UTF8String);
  45. object_setIvar(self, ivar, value);
  46. return;
  47. }else if ([mArray containsObject:isKey]) {
  48. Ivar ivar = class_getInstanceVariable([self class], isKey.UTF8String);
  49. object_setIvar(self, ivar, value);
  50. return;
  51. }
  52. // 5、如果找不到则抛出异常
  53. @throw [NSException exceptionWithName:@"CJLUnknownKeyException" reason:[NSString stringWithFormat:@"****[%@ %@]: this class is not key value coding-compliant for the key name.****",self,NSStringFromSelector(_cmd)] userInfo:nil];
  54. }

getter

image.png
image.png

  1. //取值
  2. - (nullable id)cjl_valueForKey:(NSString *)key{
  3. // 1、判断非空
  4. if (key == nil || key.length == 0) {
  5. return nil;
  6. }
  7. // 2、找到相关方法:get<Key> <key> countOf<Key> objectIn<Key>AtIndex
  8. // key 要大写
  9. NSString *Key = key.capitalizedString;
  10. // 拼接方法
  11. NSString *getKey = [NSString stringWithFormat:@"get%@",Key];
  12. NSString *countOfKey = [NSString stringWithFormat:@"countOf%@",Key];
  13. NSString *objectInKeyAtIndex = [NSString stringWithFormat:@"objectIn%@AtIndex:",Key];
  14. #pragma clang diagnostic push
  15. #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
  16. if ([self respondsToSelector:NSSelectorFromString(getKey)]) {
  17. return [self performSelector:NSSelectorFromString(getKey)];
  18. }else if ([self respondsToSelector:NSSelectorFromString(key)]){
  19. return [self performSelector:NSSelectorFromString(key)];
  20. }
  21. //集合类型
  22. else if ([self respondsToSelector:NSSelectorFromString(countOfKey)]){
  23. if ([self respondsToSelector:NSSelectorFromString(objectInKeyAtIndex)]) {
  24. int num = (int)[self performSelector:NSSelectorFromString(countOfKey)];
  25. NSMutableArray *mArray = [NSMutableArray arrayWithCapacity:1];
  26. for (int i = 0; i<num-1; i++) {
  27. num = (int)[self performSelector:NSSelectorFromString(countOfKey)];
  28. }
  29. for (int j = 0; j<num; j++) {
  30. id objc = [self performSelector:NSSelectorFromString(objectInKeyAtIndex) withObject:@(num)];
  31. [mArray addObject:objc];
  32. }
  33. return mArray;
  34. }
  35. }
  36. #pragma clang diagnostic pop
  37. // 3、判断是否响应`accessInstanceVariablesDirectly`方法,即间接访问实例变量,返回YES,继续下一步设值,如果是NO,则崩溃
  38. if (![self.class accessInstanceVariablesDirectly]) {
  39. @throw [NSException exceptionWithName:@"CJLUnKnownKeyException" reason:[NSString stringWithFormat:@"****[%@ valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.****",self] userInfo:nil];
  40. }
  41. // 4.找相关实例变量进行赋值,顺序为:_<key>、 _is<Key>、 <key>、 is<Key>
  42. // 4.1 定义一个收集实例变量的可变数组
  43. NSMutableArray *mArray = [self getIvarListName];
  44. // 例如:_name -> _isName -> name -> isName
  45. NSString *_key = [NSString stringWithFormat:@"_%@",key];
  46. NSString *_isKey = [NSString stringWithFormat:@"_is%@",Key];
  47. NSString *isKey = [NSString stringWithFormat:@"is%@",Key];
  48. if ([mArray containsObject:_key]) {
  49. Ivar ivar = class_getInstanceVariable([self class], _key.UTF8String);
  50. return object_getIvar(self, ivar);;
  51. }else if ([mArray containsObject:_isKey]) {
  52. Ivar ivar = class_getInstanceVariable([self class], _isKey.UTF8String);
  53. return object_getIvar(self, ivar);;
  54. }else if ([mArray containsObject:key]) {
  55. Ivar ivar = class_getInstanceVariable([self class], key.UTF8String);
  56. return object_getIvar(self, ivar);;
  57. }else if ([mArray containsObject:isKey]) {
  58. Ivar ivar = class_getInstanceVariable([self class], isKey.UTF8String);
  59. return object_getIvar(self, ivar);;
  60. }
  61. return @"";
  62. return @"";
  63. }

kvc 应用

  • 读/写所有属性、成员变量,包括私有、只读的。
  • 能根据 key 字符串找到方法的就 performSelector 执行方法,不能的就 object_setIvar / object_getIvar 进行读写
  • mutableArrayValueForKey: 获取可变数组后,这个数组内元素改变会触发数组自身的 set 方法 。 如果需要KVO监听可变数组的元素变化时,会用到~
  • 实现高阶消息的传递:在对容器类使用KVC时,valueForKey: 将会被传递给容器中的每一个对象,而不是对容器本身进行操作,结果会被添加到返回的容器中,这样,可以很方便的操作集合来返回另一个集合 ```objectivec //KVC实现高阶消息传递
  • (void)transmitMsg{ NSArray arrStr = @[@”english”, @”franch”, @”chinese”]; // 对数组内的每个元素执行大写方法 NSArray arrCapStr = [arrStr valueForKey:@”capitalizedString”];

    for (NSString *str in arrCapStr) {

    1. NSLog(@"%@", str);

    }

    // 对数组里的每个元素先执行大写,再执行获取长度的方法 NSArray arrCapStrLength = [arrCapStr valueForKeyPath:@”capitalizedString.length”]; for (NSNumber length in arrCapStrLength) {

    1. NSLog(@"%ld", (long)length.integerValue);

    } }

//**打印结果** 2020-10-27 11:33:43.377672+0800 CJLCustom[60035:6380757] English 2020-10-27 11:33:43.377773+0800 CJLCustom[60035:6380757] Franch 2020-10-27 11:33:43.377860+0800 CJLCustom[60035:6380757] Chinese 2020-10-27 11:33:43.378233+0800 CJLCustom[60035:6380757] 7 2020-10-27 11:33:43.378327+0800 CJLCustom[60035:6380757] 6 2020-10-27 11:33:43.378417+0800 CJLCustom[60035:6380757] 7 ``` 原文地址