object_setClass 可以将一个对象的类进转换
例如类Person
@implementation Person
@interface Person : NSObject
- (void)name;
@end
@implementation Person
- (void)name {
NSLog(@"name");
}
@end
@interface Test : NSObject
- (void)eat;
@end
@implementation Test
- (void)eat {
NSLog(@"eat");
}
@end
将Person对象的类转到Test上面
Person *p = [Person new];
object_setClass(p, [Test class]);
[p performSelector:@selector(eat)];
[p name];
打印如下
TESTRuntime[2053:65068] eat
TESTRuntime[2053:65068] -[Test name]: unrecognized selector sent to instance 0x600001dd4460
p进行类装换后, 不能在执行原来Person类的对象方法了, 只能执行Test类的对象方法
网友评论