写一个TestObject类 代码如下
TestObject.h
#import <Foundation/Foundation.h>
@interface TestObject : NSObject
@property (copy, nonatomic) NSString *name;
@property (copy, nonatomic) NSString *sex;
@end
TestObject.m
#import "TestObject.h"
#import <objc/runtime.h>
@interface TestObject()
@property (copy, nonatomic) NSString *privateName;
@property (copy, nonatomic) NSString *privateSex;
@end
@implementation TestObject
@end
方式一 使用KVC方式
TestObject *obj = [TestObject new];
[obj getIvars];
[obj setValue:@"123" forKey:@"privateName"];
NSLog(@"privateName:%@", [obj valueForKey:@"privateName"]);
方式二:
假如我们不知TestObject有哪些属性,所以我们可以利用RunTime获取所有属性
- (void)getIvars
{
unsigned int count = 0;
// 拷贝出所胡的成员变量列表
Ivar *ivars = class_copyIvarList([self class], &count);
for (int i = 0; i<count; i++) {
// 取出成员变量
Ivar ivar = ivars[i];
// 打印成员变量名字
NSLog(@"%s---", ivar_getName(ivar));
// 打印成员变量的数据类型
NSLog(@"%s---", ivar_getTypeEncoding(ivar));
NSLog(@"---------------------------------------");
}
// 释放
free(ivars);
}
假如我们要访问privateName属性,代码如下
unsigned int count = 0;
Ivar *ivars = class_copyIvarList([TestObject class], &count);
//对私有变量的更改
Ivar privateNameIvar = ivars[2];
object_setIvar(obj, privateNameIvar, @"456");
NSString *privateName = object_getIvar(obj, privateNameIvar);
NSLog(@"privateName : %@",privateName);
网友评论