确定不使用NSInvocation
,假设我有这段代码:
...
array = [NSMutableArray arrayWithObjects:@"Yoda", @"Jedi", @"Darth Vader", @"Darth Vader", @"Darth Vader" , @"Darth Vader", nil];
SEL removeObjectMessage = @selector(removeObject:inRange:);
//does array allow us to remove and object in a range? if so let's do this
if ([array respondsToSelector:removeObjectMessage]){
NSRange darthVaderRange=NSMakeRange(2, 3);
[array removeObject:@"Darth Vader"inRange:darthVaderRange];
}
我将如何以SEL removeObjectMessage的形式执行最后一行?我不得不在这个范围内放一个包装纸?我只是想看看所有混乱看起来的语法......
答案 0 :(得分:2)
你可以这样做:
if ([array respondsToSelector:removeObjectMessage]){
NSRange darthVaderRange=NSMakeRange(2, 3);
objc_msgSend(array, removeObjectMessage, @"Darth Vader", darthVaderRange);
}
虽然这看起来很脆弱......
答案 1 :(得分:1)
不幸的是,如果您传递的参数不是id
类型,则必须使用NSInvocation
对象。 (否则,您可以使用performSelector:withObject:withObject:
。)
答案 2 :(得分:1)
没有现有方法允许您传递选择器和非对象参数并获得有效的方法调用。如果它是一个只接受对象参数的方法,那么你可以[array performSelector:removeObjectMessage withObject:@"Darth Vader" withObject:someHypotheticalRangeObject
]。
但要使用NSRange,您必须使用NSInvocation(您已经说过您不想这样做)或在NSObject上创建一个类别并使用低级Objective-C运行时函数来定义一个接受选择器,对象参数和非对象参数的方法,并调用适当的方法。