2011-06-27 27 views
2

確定不使用NSInvocation,讓我們說我有這樣的代碼:語法@selector的

... 
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的形式執行最後一行?我將不得不圍繞範圍包裝?我只想看看所有這些亂七八糟的語法......

回答

1

不幸的是,如果你傳遞的參數不是id類型,則必須使用NSInvocation對象。 (否則,您可以使用performSelector:withObject:withObject:。)

+0

HM。好的...我想我只需要了解更多關於NSInvocation的知識。我可能也是,因爲我已經深入到SEL了...... –

1

沒有現成的方法允許您傳遞選擇器和非對象參數並獲得有效的方法調用。如果它只是一個只接受對象參數的方法,你會做[array performSelector:removeObjectMessage withObject:@"Darth Vader" withObject:someHypotheticalRangeObject]。

但要做到這一點與NSRange,你將不得不使用NSInvocation(你說你不想做),或者在NSObject上創建一個類別,並使用底層的Objective-C運行時函數定義一個採用選擇器,對象參數和非對象參數並調用相應方法的方法。

2

你可以這樣做:

if ([array respondsToSelector:removeObjectMessage]){ 
    NSRange darthVaderRange=NSMakeRange(2, 3); 
    objc_msgSend(array, removeObjectMessage, @"Darth Vader", darthVaderRange); 
} 

雖然這似乎是相當脆弱......