-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.m
57 lines (43 loc) · 1.56 KB
/
main.m
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
//
// main.m
//
// Copyright © 2018 H4n. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <objc/objc-runtime.h>
Class Car;
NSNumber *wheelsGetter(id self, SEL _cmd) {
Ivar ivar = class_getInstanceVariable(Car, "_wheels");
return object_getIvar(self, ivar);
}
void wheelsSetter(id self, SEL _cmd, NSNumber* newCount) {
Ivar ivar = class_getInstanceVariable(Car, "_wheels");
id oldCount = object_getIvar(self, ivar);
if (oldCount != newCount) object_setIvar(self, ivar, [newCount copy]);
}
void createClass() {
// allocate class
Car = objc_allocateClassPair([NSObject class], "Car", 0);
// add iVar
class_addIvar(Car, "_wheels", sizeof(NSNumber*), log2(sizeof(NSNumber*)), @encode(NSNumber*));
// add property
objc_property_attribute_t type = { "T", "@\"NSNumber\"" };
objc_property_attribute_t backingivar = { "V", "_wheels" };
objc_property_attribute_t attrs[] = { type, backingivar };
class_addProperty(Car, "wheels", attrs, 2);
// add getter method
class_addMethod(Car, @selector(wheels), (IMP)wheelsGetter, "@@:");
// add setter method
class_addMethod(Car, @selector(setWheels:), (IMP)wheelsSetter, "v@:@");
// register class
objc_registerClassPair(Car);
}
int main(int argc, const char * argv[]) {
@autoreleasepool {
createClass();
id car = [[Car alloc] init];
[car performSelector:@selector(setWheels:) withObject:@4];
NSLog(@"%@", [car performSelector:@selector(wheels)]);
}
return 0;
}