如何访问并修改一个类的私有属性?

一个类的私有属性是不能通过.运算符来调用的,那么如何修改其值呢?

方式一:通过KVC访问并修改

关于KVC的相关介绍详见:

 KVC与KVO理解


方式二:通过runtime访问并修改

关于runtime的相关介绍详见:

iOS~runtime理解

代码示例:


Person.h


Person.m


main

备忘:

unsigned int count;

//获取属性列表

objc_property_t * propertyList = class_copyPropertyList([self class], &count);

for (unsigned int i = 0; i < count; i++) {

const char * propertyName = property_getName(propertyList[i]);

NSLog(@"property---->%@", [NSString stringWithUTF8String: propertyName]);

}

//获取方法列表

Method * methodList = class_copyMethodList([self class], &count);

for (unsigned int i; i < count; i++) {

Method method = methodList[i];

NSLog(@"method---->%@", NSStringFromSelector(method_getName(method)));

}

//获取成员变量列表

Ivar * ivarList = class_copyIvarList([self class], &count);

for (unsigned int i; i < count; i++) {

Ivar myIvar = ivarList[i];

const char * ivarName = ivar_getName(myIvar);

NSLog(@"Ivar---->%@", [NSString stringWithUTF8String: ivarName]);

}

//获取协议列表

__unsafe_unretained Protocol * *protocolList = class_copyProtocolList([self class], &count);

for (unsigned int i; i < count; i++) {

Protocol * myProtocal = protocolList[i];

const char * protocolName = protocol_getName(myProtocal);

NSLog(@"protocol---->%@", [NSString stringWithUTF8String: protocolName]);

}

输出:

2016-10-09 20:52:51.694 RuntimeDemo[1114:260312]属性名=_name

2016-10-09 20:52:51.694 RuntimeDemo[1114:260312] cardId:2222

2016-10-09 20:52:51.695 RuntimeDemo[1114:260312]属性名=_address

2016-10-09 20:52:51.695 RuntimeDemo[1114:260312] cardId:2222

2016-10-09 20:52:51.695 RuntimeDemo[1114:260312]属性名=_cardId

2016-10-09 20:52:51.695 RuntimeDemo[1114:260312] cardId:2222

推荐阅读更多精彩内容