自定義類Honzon
鞠呈,一個私有成員變量test
和一個打印方法logTest
@interface Honzon : NSObject
- (void)logTest;
@end
@interface Honzon ()
@property(nonatomic, copy)NSString *test;
@end
@implementation Honzon
- (void)logTest {
NSLog(@"test: %@", self.test);
}
@end
KVC
Honzon *h1 = [Honzon new];
[h1 setValue:@"h1 test" forKey:@"test"];
[h1 logTest];
//-> test: h1 test
調(diào)用私有方法
通過OC的運行時,調(diào)用私有變量的setter
方法
//消息發(fā)送
Honzon *h2 = [Honzon new];
if ([h2 respondsToSelector:@selector(setTest:)]) {
[h2 performSelector:@selector(setTest:) withObject:@"h2 test"];
NSLog(@"%@",[h2 performSelector:@selector(test)]);
//-> h2 test
// objc_msgSend(h2,@selector(setTest:),@"h2 test");
// [h2 logTest];
}
[h2 logTest];
//-> test: h2 test
當(dāng)然也可以獲取方法列表去循環(huán)查找
Ivar
先取得ivar
,然后通過object_setIvar
修改成員變量的值
//runtime 獲取ivar
// 獲取類的所有成員變量
Honzon *h3 = [Honzon new] ;
unsigned int count = 0;//count記錄變量的數(shù)量
Ivar *members = class_copyIvarList([h3 class], &count);
for (NSUInteger i = 0; i < count; i++) {
Ivar ivar = members[i];
// 取得屬性名并轉(zhuǎn)成字符串類型
const char *memberName = ivar_getName(ivar);
NSString *memberNameString = [NSString stringWithUTF8String:memberName];
if ([memberNameString isEqualToString:@"_test"]) {
// 修改屬性值
object_setIvar(h3, ivar, @"h3 test");
break;
}
}
[h3 logTest];
free(members);
//-> test: h3 test
Honzon *h4 = [Honzon new] ;
Ivar _testNameIvar = class_getInstanceVariable([h4 class], "_test");
object_setIvar(h4, _testNameIvar, @"h4 test");
[h4 logTest];
//-> test: h4 test
NSValue包裝結(jié)構(gòu)體
自定義結(jié)構(gòu)體
struct HZStruct {
int version;
char *name;
};
包裝結(jié)構(gòu)體
struct HZStruct hzStruct = {
.version = 0,
.name = "hzStruct"
};
NSValue *hz1 = [NSValue value:&hzStruct withObjCType:@encode(struct HZStruct)];
解包結(jié)構(gòu)體
struct HZStruct hzStruct2;
[hz1 getValue:&hzStruct2];
NSLog(@"%d %s",hzStruct2.version,hzStruct2.name);
//-> 0 hzStruct
NSValue
針對系統(tǒng)的部分結(jié)構(gòu)體做了優(yōu)化阶牍,比如valueWithRect
,不用像自定義結(jié)構(gòu)體這樣