Created
July 12, 2017 11:49
-
-
Save HarrisHan/b339ba8d0aa2c511ba24fd6c577d8f19 to your computer and use it in GitHub Desktop.
Dynamically create Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (void)createClass | |
{ | |
Class MyClass = objc_allocateClassPair([NSObject class], "myclass", 0); | |
//添加一个NSString的变量,第四个参数是对其方式,第五个参数是参数类型 | |
if (class_addIvar(MyClass, "itest", sizeof(NSString *), 0, "@")) { | |
NSLog(@"add ivar success"); | |
} | |
//myclasstest是已经实现的函数,"v@:"这种写法见参数类型连接 | |
class_addMethod(MyClass, @selector(myclasstest:), (IMP)myclasstest, "v@:"); | |
//注册这个类到runtime系统中就可以使用他了 | |
objc_registerClassPair(MyClass); | |
//生成了一个实例化对象 | |
id myobj = [[MyClass alloc] init]; | |
NSString *str = @"asdb"; | |
//给刚刚添加的变量赋值 | |
// object_setInstanceVariable(myobj, "itest", (void *)&str);在ARC下不允许使用 | |
[myobj setValue:str forKey:@"itest"]; | |
//调用myclasstest方法,也就是给myobj这个接受者发送myclasstest这个消息 | |
[myobj myclasstest:10]; | |
} | |
//这个方法实际上没有被调用,但是必须实现否则不会调用下面的方法 | |
- (void)myclasstest:(int)a | |
{ | |
} | |
//调用的是这个方法 | |
static void myclasstest(id self, SEL _cmd, int a) //self和_cmd是必须的,在之后可以随意添加其他参数 | |
{ | |
Ivar v = class_getInstanceVariable([self class], "itest"); | |
//返回名为itest的ivar的变量的值 | |
id o = object_getIvar(self, v); | |
//成功打印出结果 | |
NSLog(@"%@", o); | |
NSLog(@"int a is %d", a); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment