我正在学习Objective-C运行时,并尝试使用method_exchangeImplementations
来交换NSMutableArray
的addObject:
方法和removeObject:
方法。
int main(int argc, const char * argv[]) {
@autoreleasepool {
Method removeMethod = class_getInstanceMethod(NSMutableArray.class, @selector(removeObject:));
Method addMethod = class_getInstanceMethod(NSMutableArray.class, @selector(addObject:));
method_exchangeImplementations(addMethod, removeMethod);
NSMutableArray *array = [[NSMutableArray alloc] init];
NSObject *obj = [[NSObject alloc] init];
[array removeObject:obj];
NSLog(@"%lu", (unsigned long)array.count); // expect print 1, actual print 1
[array addObject:obj];
NSLog(@"%lu", (unsigned long)array.count); // expect print 0, actual print 2
}
return 0;
}
我期望交换添加/删除功能,但似乎只有removeObject:
已经交换到addObject:
,addObject:
仍然是addObject到数组,现在我有两个NSMutableArray
的addObject方法
我不确定原因。我尝试交换其他方法,如NSString
的uppercaseString/lowercaseString
,工作正确。
好了,我解决了问题。谢谢@Willeke的提示。
我的数组的真正类不是NSMutableArray
,所以在class_getInstanceMethod
中使用NSMutableArray.class
不能得到正确的方法。使用[array class]
是答案。
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSMutableArray *array = [[NSMutableArray alloc] init];
Method removeMethod = class_getInstanceMethod([array class], @selector(removeObject:));
Method addMethod = class_getInstanceMethod([array class], @selector(addObject:));
method_exchangeImplementations(addMethod, removeMethod);
NSObject *obj = [[NSObject alloc] init];
[array removeObject:obj];
NSLog(@"%lu", (unsigned long)array.count); // expect print 1, actual print 1
[array addObject:obj];
NSLog(@"%lu", (unsigned long)array.count); // expect print 0, actual print 0
}
return 0;
}