成员变量
1、成员变量的定义
Ivar: 实例变量类型,是一个指向objc_ivar结构体的指针
typedef struct objc_ivar *Ivar;
2、相关函数
// 获取所有成员变量
class_copyIvarList
// 获取成员变量名
ivar_getName
// 获取成员变量类型编码
ivar_getTypeEncoding
// 获取指定名称的成员变量
class_getInstanceVariable
// 获取某个对象成员变量的值
object_getIvar
// 设置某个对象成员变量的值
object_setIvar
说明:
property_getAttributes函数返回objc_property_attribute_t结构体列表,objc_property_attribute_t结构体包含name和value,常用的属性如下:
属性类型 name值:T value:变化
编码类型 name值:C(copy) &(strong) W(weak)空(assign) 等 value:无
非/原子性 name值:空(atomic) N(Nonatomic) value:无
变量名称 name值:V value:变化
使用property_getAttributes获得的描述是property_copyAttributeList能获取到的所有的name和value的总体描述,如 T@"NSDictionary",C,N,V_dict1
3、实例应用
<!--Person.h文件-->
@interface Person : NSObject
{
NSString *address;
}
@property(nonatomic,strong)NSString *name;
@property(nonatomic,assign)NSInteger age;
//遍历获取Person类所有的成员变量IvarList
- (void) getAllIvarList {
unsigned int methodCount = 0;
Ivar * ivars = class_copyIvarList([Person class], &methodCount);
for (unsigned int i = 0; i < methodCount; i ++) {
Ivar ivar = ivars[i];
const char * name = ivar_getName(ivar);
const char * type = ivar_getTypeEncoding(ivar);
NSLog(@"Person拥有的成员变量的类型为%s,名字为 %s ",type, name);
}
free(ivars);
}
<!--打印结果-->
2016-06-15 20:26:39.412 demo-Cocoa之method swizzle[17798:2565569] Person拥有的成员变量的类型为@"NSString",名字为 address
2016-06-15 20:26:39.413 demo-Cocoa之method swizzle[17798:2565569] Person拥有的成员变量的类型为@"NSString",名字为 _name
2016-06-15 20:26:39.413 demo-Cocoa之method swizzle[17798:2565569] Person拥有的成员变量的类型为q,名字为 _age
属性
1、属性的定义
objc_property_t:声明的属性的类型,是一个指向objc_property结构体的指针
typedef struct objc_property *objc_property_t;
2、相关函数
// 获取所有属性
class_copyPropertyList
说明:使用class_copyPropertyList并不会获取无@property声明的成员变量
// 获取属性名
property_getName
// 获取属性特性描述字符串
property_getAttributes
// 获取所有属性特性
property_copyAttributeList
3、实例应用










