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.
* The search order is:
* Accessor methods: * * getKey * key * * If the receiver's class allows +accessInstanceVariablesDirectly * it continues with private accessors: * * _getKey * _key * * and then instance variables: * * key * _key * * 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中几个关键方法的实现.

你可能感兴趣的:(KVC)