KVC

本文章的代码来源gnustep-base-1.26.0 ,应该和系统的实现还是不一样的,仅供参考 :

常用方法

+ (BOOL) accessInstanceVariablesDirectly; // 是否允许访问成员变量,默认是yes

- (void) setValue: (id)anObject forKey: (NSString*)aKey;
- (void) setValue: (id)anObject forKeyPath: (NSString*)aKey;
- (void) setValue: (id)anObject forUndefinedKey: (NSString*)aKey;

/**
 * Returns the value associated with the supplied key as an object.
 * Scalar attributes are converted to corresponding objects.<br />
 * The search order is:<br/>
 * Accessor methods:
 * <list>
 *  <item>getKey</item>
 *  <item>key</item>
 * </list>
 * If the receiver's class allows +accessInstanceVariablesDirectly
 * it continues with private accessors:
 * <list>
 *  <item>_getKey</item>
 *  <item>_key</item>
 * </list>
 * and then instance variables:
 * <list>
 *  <item>key</item>
 *  <item>_key</item>
 * </list>
 * Invokes -setValue:forUndefinedKey:
 * if no accessor mechanism can be found
 * and raises NSInvalidArgumentException if the accessor method takes
 * any arguments or the type is unsupported (e.g. structs).
 */
- (id) valueForKey: (NSString*)aKey;
- (id) valueForKeyPath: (NSString*)aKey;
- (id) valueForUndefinedKey: (NSString*)aKey;

setValue: forKey:

- (void) setValue: (id)anObject forKey: (NSString*)aKey
{
  unsigned  size = [aKey length] * 8; // 乘以8是为了兼容编码长度问题
  char      key[size + 1]; // +1 是为了转成的字符串最后有个'/0'终止符
#ifdef WANT_DEPRECATED_KVC_COMPAT //  要废弃,但是要兼容
  IMP       o = [self methodForSelector: @selector(takeValue:forKey:)];

  setupCompat();
  if (o != takeValue && o != takeValueKVO)
    {
      (*o)(self, @selector(takeValue:forKey:), anObject, aKey); // 调用takeValue:forKey:方法
      return;
    }
#endif

  [aKey getCString: key
     maxLength: size + 1
      encoding: NSUTF8StringEncoding]; // 转成 char * 字符串
  size = strlen(key);
  SetValueForKey(self, anObject, key, size); // 调用 SetValueForKey 函数
}

可以看到,调用了takeValue:forKey方法或者SetValueForKey函数

takeValue:forKey:

- (void) takeValue: (id)anObject forKey: (NSString*)aKey
{
  SEL       sel = 0;
  const char    *type = 0;
  int       off = 0;
  unsigned  size = [aKey length] * 8;
  char      key[size + 1];

  GSOnceMLog(@"This method is deprecated, use -setValue:forKey:"); // 方法废弃
  [aKey getCString: key
     maxLength: size + 1
      encoding: NSUTF8StringEncoding]; // 转成C语言字符串, 目测接下来的实现会和SetValueForKey一样
  size = strlen(key); // 获得转换后的char*字符串长度

  if (size > 0)
    {
      const char    *name;
      char      buf[size + 6];
      char      lo;
      char      hi;

      strncpy(buf, "_set", 4);
      strncpy(&buf[4], key, size); // 拼接成_setKey的格式
      lo = buf[4];
      hi = islower(lo) ? toupper(lo) : lo;// 如果首字母是小写,转成大写,驼峰命名法
      buf[4] = hi;
      buf[size + 4] = ':'; // 转成方法 
      buf[size + 5] = '\0';

      name = &buf[1];   // setKey:
      type = NULL;
      sel = sel_getUid(name); // 寻找或注册方法选择器
      if (sel == 0 || [self respondsToSelector: sel] == NO) // 如果没有实现 setKey方法,就去寻找_setKey方法
    {
      name = buf;   // _setKey:
      sel = sel_getUid(name);
      if (sel == 0 || [self respondsToSelector: sel] == NO)
        {
          sel = 0;
          if ([[self class] accessInstanceVariablesDirectly] == YES) // 是否能访问成员变量
        {
          buf[size + 4] = '\0';
          buf[3] = '_';
          buf[4] = lo;
          name = &buf[4];   // 寻找key成员变量
          if (GSObjCFindVariable(self, name, &type, &size, &off) == NO)
            {
              name = &buf[3];   // 寻找_key 成员变量
              GSObjCFindVariable(self, name, &type, &size, &off);
            }
        }
        }
    }
    }
  GSObjCSetVal(self, key, anObject, sel, type, size, off);
}

SetValueForKey

static void
SetValueForKey(NSObject *self, id anObject, const char *key, unsigned size)
{
  SEL       sel = 0;
  const char    *type = 0;
  int       off = 0;

  if (size > 0)
    {
      const char    *name;
      char      buf[size + 6];
      char      lo;
      char      hi;

      strncpy(buf, "_set", 4);
      strncpy(&buf[4], key, size);
      lo = buf[4];
      hi = islower(lo) ? toupper(lo) : lo;
      buf[4] = hi;
      buf[size + 4] = ':';
      buf[size + 5] = '\0';

      name = &buf[1];   // setKey:
      type = NULL;
      sel = sel_getUid(name);
      if (sel == 0 || [self respondsToSelector: sel] == NO)
    {
      name = buf;   // _setKey:
      sel = sel_getUid(name);
      if (sel == 0 || [self respondsToSelector: sel] == NO)
        {
          sel = 0;
          if ([[self class] accessInstanceVariablesDirectly] == YES)
        {
          buf[size + 4] = '\0';
          buf[3] = '_';
          buf[4] = lo;
          name = &buf[3];   // _key
          if (GSObjCFindVariable(self, name, &type, &size, &off) == NO)
            {
              buf[4] = hi;
              buf[3] = 's';
              buf[2] = 'i';
              buf[1] = '_';
              name = &buf[1];   // _isKey
              if (GSObjCFindVariable(self,
            name, &type, &size, &off) == NO)
            {
              buf[4] = lo;
              name = &buf[4];   // key
              if (GSObjCFindVariable(self,
                name, &type, &size, &off) == NO)
                {
                  buf[4] = hi;
                  buf[3] = 's';
                  buf[2] = 'i';
                  name = &buf[2];   // isKey
                  GSObjCFindVariable(self,
                name, &type, &size, &off);
                }
            }
            }
        }
        }
      else
        {
          GSOnceFLog(@"Key-value access using _setKey: is deprecated:");
        }
    }
    }
  GSObjCSetVal(self, key, anObject, sel, type, size, off);
}

- (void) takeValue: (id)anObject forKey: (NSString*)aKey 实现基本上一致,只是在访问成员变量的时候,会再检索 _isKeyisKey

GSObjCFindVariable 寻找成员变量

BOOL
GSObjCFindVariable(id obj, const char *name,
  const char **type, unsigned int *size, int *offset)
{
  Class     class = object_getClass(obj);
  Ivar      ivar = class_getInstanceVariable(class, name); // 获取成员变量

  if (ivar == 0)
    {
      return NO;
    }
  else
    {
      const char    *enc = ivar_getTypeEncoding(ivar); // 获取类型

      if (type != 0)
    {
      *type = enc;
    }
      if (size != 0)
    {
      NSUInteger    s;
      NSUInteger    a;

      NSGetSizeAndAlignment(enc, &s, &a);
      *size = s; // 获取成员变量size
    }
      if (offset != 0)
    {
      *offset = ivar_getOffset(ivar); // 成员变量的偏移量
    }
      return YES;
    }
}

GSObjCSetVal 调用setter方法或者直接修改成员变量

void
GSObjCSetVal(NSObject *self, const char *key, id val, SEL sel,
  const char *type, unsigned size, int offset)
{
  static NSNull     *null = nil;
  NSMethodSignature *sig = nil;

  if (null == nil)
    {
      null = [NSNull new]; 
    }
  if (sel != 0) // 如果sel存在,则需要获取参数类型,如果sel不存在,则类型是传过来的
    {
      sig = [self methodSignatureForSelector: sel]; // 获得方法签名
      if ([sig numberOfArguments] != 3) // 参数必须是3个
    {
      [NSException raise: NSInvalidArgumentException
              format: @"key-value set method has wrong number of args"];
    }
      type = [sig getArgumentTypeAtIndex: 2]; // 第三参数的type
    }
  if (type == NULL)// 没有找到对应的赋值方式
    {
      [self setValue: val forUndefinedKey:
    [NSString stringWithUTF8String: key]];
    }
  else if ((val == nil || val == null) && *type != _C_ID && *type != _C_CLASS) // 如果obj 等于 null
    {
      [self setNilValueForKey: [NSString stringWithUTF8String: key]];
    }
  else
    {
      switch (*type)
    {
      case _C_ID:
      case _C_CLASS: // 调用方法,或者直接复制
        {
          id    v = val;

          if (sel == 0)
        {
          id *ptr = (id *)((char *)self + offset);

          ASSIGN(*ptr, v); // retain v
        }
          else
        {
          void  (*imp)(id, SEL, id) =
            (void (*)(id, SEL, id))[self methodForSelector: sel];

          (*imp)(self, sel, val);
        }
        }
        break;

      case _C_CHR:
        {
          char  v = [val charValue];

          if (sel == 0)
        {
          char *ptr = (char *)((char *)self + offset);

          *ptr = v;
        }
          else
        {
          void  (*imp)(id, SEL, char) =
            (void (*)(id, SEL, char))[self methodForSelector: sel];

          (*imp)(self, sel, v);
        }
        }
        break;
···
// 中间省略的代码基本上都是根据类型直接给成员变量赋值或调用方法
···
      default:
            [self setValue: val forUndefinedKey:
          [NSString stringWithUTF8String: key]];
    }
    }
}

setValue:forKeyPath:

- (void) setValue: (id)anObject forKeyPath: (NSString*)aKey
{
  NSRange       r = [aKey rangeOfString: @"." options: NSLiteralSearch]; // 寻找 . 
#ifdef WANT_DEPRECATED_KVC_COMPAT
  IMP           o = [self methodForSelector: @selector(takeValue:forKeyPath:)];

  setupCompat();
  if (o != takePath && o != takePathKVO)
    {
      (*o)(self, @selector(takeValue:forKeyPath:), anObject, aKey);
      return;
    }
#endif

  if (r.length == 0) // 如果没有找到 . 则直接调用 setValue:forKey:
    {
      [self setValue: anObject forKey: aKey];
    }
  else
    {
      NSString  *key = [aKey substringToIndex: r.location];
      NSString  *path = [aKey substringFromIndex: NSMaxRange(r)];
      
      [[self valueForKey: key] setValue: anObject forKeyPath: path]; // 递归调用,直到 没有 `.`
    }
}

takeValue:forKeyPath:

- (void) takeValue: (id)anObject forKeyPath: (NSString*)aKey
{
  NSRange   r = [aKey rangeOfString: @"." options: NSLiteralSearch];

  GSOnceMLog(@"This method is deprecated, use -setValue:forKeyPath:");
  if (r.length == 0)
    {
      [self takeValue: anObject forKey: aKey];
    }
  else
    {
      NSString  *key = [aKey substringToIndex: r.location];
      NSString  *path = [aKey substringFromIndex: NSMaxRange(r)];

      [[self valueForKey: key] takeValue: anObject forKeyPath: path];
    }
}

可以发现,也是递归调用,直到没有 .

valueForKey:

- (id) valueForKey: (NSString*)aKey
{
  unsigned  size = [aKey length] * 8;
  char      key[size + 1];

  [aKey getCString: key
     maxLength: size + 1
      encoding: NSUTF8StringEncoding]; // 转成 char * 字符串
  size = strlen(key);
  return ValueForKey(self, key, size);
}

ValueForKey

static id ValueForKey(NSObject *self, const char *key, unsigned size)
{
  SEL       sel = 0;
  int       off = 0;
  const char    *type = NULL;

  if (size > 0)
    {
      const char    *name;
      char      buf[size + 5];
      char      lo;
      char      hi;

      strncpy(buf, "_get", 4);
      strncpy(&buf[4], key, size);
      buf[size + 4] = '\0';
      lo = buf[4];
      hi = islower(lo) ? toupper(lo) : lo;
      buf[4] = hi;

      name = &buf[1];   // getKey
      sel = sel_getUid(name);
      if (sel == 0 || [self respondsToSelector: sel] == NO)
    {
      buf[4] = lo;
      name = &buf[4];   // key
      sel = sel_getUid(name);
      if (sel == 0 || [self respondsToSelector: sel] == NO)
        {
              buf[4] = hi;
              buf[3] = 's';
              buf[2] = 'i';
              name = &buf[2];   // isKey
              sel = sel_getUid(name);
              if (sel == 0 || [self respondsToSelector: sel] == NO)
                {
                  sel = 0;
                }
        }
    }

      if (sel == 0 && [[self class] accessInstanceVariablesDirectly] == YES)
    {
      buf[4] = hi;
      name = buf;   // _getKey
      sel = sel_getUid(name);
      if (sel == 0 || [self respondsToSelector: sel] == NO)
        {
          buf[4] = lo;
          buf[3] = '_';
          name = &buf[3];   // _key
          sel = sel_getUid(name);
          if (sel == 0 || [self respondsToSelector: sel] == NO)
        {
          sel = 0;
        }
        }
      if (sel == 0)
        {
          if (GSObjCFindVariable(self, name, &type, &size, &off) == NO) // 寻找成员变量 先找 _key
        {
                  buf[4] = hi;
                  buf[3] = 's';
                  buf[2] = 'i';
                  buf[1] = '_';
                  name = &buf[1];   // _isKey
          if (!GSObjCFindVariable(self, name, &type, &size, &off))
                    {
                       buf[4] = lo;
                       name = &buf[4];      // key
               if (!GSObjCFindVariable(self, name, &type, &size, &off))
                         {
                            buf[4] = hi;
                            buf[3] = 's';
                            buf[2] = 'i';
                            name = &buf[2]; // isKey
                            GSObjCFindVariable(self, name, &type, &size, &off);
                         }
                    }
        }
        }
    }
    }
  return GSObjCGetVal(self, key, sel, type, size, off);
}

GSObjCGetVal

id
GSObjCGetVal(NSObject *self, const char *key, SEL sel,
           const char *type, unsigned size, int offset)
{
  NSMethodSignature *sig = nil;

  if (sel != 0)
    {
      sig = [self methodSignatureForSelector: sel]; // 方法签名
      if ([sig numberOfArguments] != 2) // 参数必须是两个
    {
      [NSException raise: NSInvalidArgumentException
              format: @"key-value get method has wrong number of args"];
    }
      type = [sig methodReturnType]; // 返回值的类型
    }
  if (type == NULL) // 没有找到方法或者成员变量
    {
      return [self valueForUndefinedKey: [NSString stringWithUTF8String: key]];
    }
  else
    {
      id    val = nil;

      switch (*type) // 根据返回值类型,调用方法或者直接访问成员变量
    {
      case _C_ID:
      case _C_CLASS:
        {
          id    v;

          if (sel == 0)
        {
          v = *(id *)((char *)self + offset);
        }
          else
        {
          id    (*imp)(id, SEL) =
            (id (*)(id, SEL))[self methodForSelector: sel];

          v = (*imp)(self, sel);
        }
          val = v;
        }
        break;

      case _C_CHR:
        {
          signed char   v;

          if (sel == 0)
        {
          v = *(char *)((char *)self + offset);
        }
          else
        {
          signed char   (*imp)(id, SEL) =
            (signed char (*)(id, SEL))[self methodForSelector: sel];

          v = (*imp)(self, sel);
        }
          val = [NSNumber numberWithChar: v];
        }
        break;

      default:
#ifdef __GNUSTEP_RUNTIME__
        {
          Class     cls;
          struct objc_slot  *type_slot;
          SEL       typed;
          struct objc_slot  *slot;

          cls = [self class];
          type_slot = objc_get_slot(cls, @selector(retain));
          typed = GSSelectorFromNameAndTypes(sel_getName(sel), NULL);
          slot = objc_get_slot(cls, typed);
          if (strcmp(slot->types, type_slot->types) == 0)
        {
          return slot->method(self, typed);
        }
        }
#endif
        val = [self valueForUndefinedKey:
          [NSString stringWithUTF8String: key]];
    }
      return val;
    }
}

总结

以上就是GUNStep关于KVC中几个关键方法的实现.

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,080评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,422评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,630评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,554评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,662评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,856评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,014评论 3 408
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,752评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,212评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,541评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,687评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,347评论 4 331
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,973评论 3 315
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,777评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,006评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,406评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,576评论 2 349

推荐阅读更多精彩内容