Objective-C method_exchangeImplementations结果不符合预期



我正在学习Objective-C运行时,并尝试使用method_exchangeImplementations来交换NSMutableArrayaddObject:方法和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方法

我不确定原因。我尝试交换其他方法,如NSStringuppercaseString/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;
}

相关内容

  • 没有找到相关文章