IOS 中runtime使用方法整理

2020-01-18 22:17:58于海丽

4.添加属性(方式2)


ClassOne *one = [ClassOne new];
objc_setAssociatedObject(one, "objTag", @"value", OBJC_ASSOCIATION_COPY);
NSString *value = objc_getAssociatedObject(one, "objTag");
NSLog(@"通过Associate设置:%@",value);

5.获取类的名称


ClassOne *one = [ClassOne new];
const char *className = object_getClassName(one);
NSLog(@"className:%@",[NSString stringWithUTF8String:className]);

6.获取一个类的所有方法


UInt count;
Method *methods = class_copyMethodList([ClassOne class], &count);
for (int i = 0; i < count; i++) {
  Method method = methods[i];
  SEL sel = method_getName(method);
  NSLog(@"方法名:%@",NSStringFromSelector(sel));
}

7.获取一个类的所有属性


uint propertyCount;
objc_property_t *ps = class_copyPropertyList([ClassOne class], &propertyCount);
for (uint i = 0; i < propertyCount; i++) {
  objc_property_t property = ps[i];
  const char *propertyName = property_getName(property);
  const char *propertyAttributes = property_getAttributes(property);
  NSLog(@"propertyName:%@",[NSString stringWithUTF8String:propertyName]);
  NSLog(@"propertyAttributes:%@",[NSString stringWithUTF8String:propertyAttributes]);
}

8.获取类的所有成员变量


uint ivarCount;
Ivar *ivars = class_copyIvarList([ClassOne class], &ivarCount);
for (uint i = 0; i < ivarCount; i++) {
  Ivar ivar = ivars[i];
  const char *ivarName = ivar_getName(ivar);
  NSLog(@"ivarName:%@",[NSString stringWithUTF8String:ivarName]);
}

9.获得成员变量类型

 


uint ivarCount;
Ivar *ivars = class_copyIvarList([ClassOne class], &ivarCount);
for (uint i = 0; i < ivarCount; i++) {
  Ivar ivar = ivars[i];
  const char *ivarName = ivar_getName(ivar);
  const char *type = ivar_getTypeEncoding(ivar);
  NSLog(@"ivarName=%@,type=%@",[NSString stringWithUTF8String:ivarName],[NSString stringWithUTF8String:type]);
}

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!


注:相关教程知识阅读请移步到IOS开发频道。