消息转发过程中, 如果需要在分类中访问/设置私有变量或者属性, 可以参照如下方法。
#import <objc/runtime.h>
void startEngine(id self, SEL _cmd, NSString *brand, NSString *name) {
// 访问成员变量
Ivar engineIvar = class_getInstanceVariable([self class], "_engine");
if (engineIvar) {
id engineValue = object_getIvar(self, engineIvar);
NSLog(@"---我的engineValue:%@",engineValue);
// 使用 engineValue 进行操作
object_setIvar(self, engineIvar, @(8888));
id engineValue1 = object_getIvar(self, engineIvar);
NSLog(@"---我的engineValue1:%@",engineValue1);
}
// 设置成员变量
Ivar mileageIvar = class_getInstanceVariable([self class], "_mileage");
if (mileageIvar) {
id mileageValue = object_getIvar(self, mileageIvar);
NSLog(@"---我的mileageValue:%@",mileageValue);
object_setIvar(self, mileageIvar, @(10000));
id mileageValue1 = object_getIvar(self, mileageIvar);
NSLog(@"---我的mileageValue1:%@",mileageValue1);
}
SEL propertyGetter = NSSelectorFromString(@"horsepower");//访问属性,
SEL propertySetter = NSSelectorFromString(@"setHorsepower:");//设置属性
if ([self respondsToSelector:propertyGetter]) {
id propertyValue = [self performSelector:propertyGetter];
NSLog(@"---horsepower2 : %@,", propertyValue);
}
if ([self respondsToSelector:propertySetter]) {
[self performSelector:propertySetter withObject:@(200)];
id propertyValue = [self performSelector:propertyGetter];
NSLog(@"---- horsepower1 : %@,", propertyValue);
}
}