使用Runtime动态创建一个类

关键代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#import "ViewController.h"
#import <objc/runtime.h>
 
@interface ViewController ()
@end
 
@implementation ViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
 
    // 动态创建一个类
    Class newClass = objc_allocateClassPair(NSObject.class, "SAObject", 0);
    // 添加类成员
    class_addIvar(newClass, "name", sizeof(NSString *), 1<<0, @encode(NSString *));
    class_addIvar(newClass, "age", sizeof(int), 1<<0, @encode(int));
    // 注册类
    objc_registerClassPair(newClass);
 
    // 遍历类成员
    unsigned int outCount;
    Ivar *ivars = class_copyIvarList(newClass, &outCount);
    for (int i = 0; i < outCount; i++) {
        Ivar ivar = ivars[i];
        NSLog(@"%s %s", ivar_getName(ivar), ivar_getTypeEncoding(ivar));
    }
 
    // 内存释放
    free(ivars);
    objc_disposeClassPair(newClass);
}
 
@end

打印结果:
2018-11-22 10:36:43.829729+0800 runtime[2399:357753] name @
2018-11-22 10:36:43.829862+0800 runtime[2399:357753] age i

Leave a Reply