#import <Foundation/Foundation.h> @interface CustomClass : NSObject -(void)fun1; @end @interface CustomOtherClass : NSObject -(void)fun2; @end
#import "TestClass.h" #import <objc/runtime.h> @implementation TestClass + (BOOL)resolveInstanceMethod:(SEL)sel { Method exchangeM = class_getInstanceMethod([self class], @selector(eatWithPersonName:)); //拿到IMP指针 class_addMethod([self class], sel, class_getMethodImplementation(self, @selector(eatWithPersonName:)),method_getTypeEncoding(exchangeM)); return YES; } - (void)eatWithPersonName:(NSString *)name { NSLog(@"Person %@ start eat ",name); } @end
/**
对象拷贝
*/
-(void)copyObj{
CustomClass *obj = [CustomClass new];
NSLog(@"对象拷贝:%p",&obj);
//完全是一个新的对象
id objTest = object_copy(obj,sizeof(obj));
NSLog(@"%p", &objTest);
[objTest fun1];
}
/**
对象释放
*/
-(void)objectDispose{
CustomClass *obj = [CustomClass new];
(void)(NSLog(@"---%ld",obj.retainCount)),
object_dispose(obj);
//(void)(NSLog(@"---%ld",obj.retainCount)),
//[obj release];
//NSLog(@"---%ld",obj.retainCount);
//[obj fun1];
}
/**
更改对象的类
*/
-(void)setClassTest{
CustomClass *obj = [CustomClass new];
[obj fun1];
Class aclass = object_setClass(obj, [CustomOtherClass class]);
//obj 对象的类被更改了 swap the isa to an isa
NSLog(@"aClass:%@",NSStringFromClass(aclass));
NSLog(@"obj class:%@",NSStringFromClass([obj class]));
[obj fun2];
}
-(void)getClassTest{
CustomClass *obj = [CustomClass new];
Class alogClass = object_getClass(obj);
NSLog(@"--get:%@",NSStringFromClass(alogClass));
}
/**
获取对象的类名
*/
- (void) getClassName{
CustomClass *obj = [CustomClass new];
NSString *className = [NSString stringWithCString:object_getClassName(obj) encoding:NSUTF8StringEncoding];
NSLog(@"className:%@",className);
}
/**
动态给一个类添加方法
*/
- (void)oneParam{
TestClass *instance = [[TestClass alloc]init];
//方法添加
[instance performSelector:@selector(eatWithPersonName:) withObject:@"mujin"];
}