我正在嘗試在 Objective C 中撰寫一個方法,該方法將 @selector 作為引數。它作業正常 - 前提是我不希望選擇器本身有引數(我有)。
- (void) testWithInput:(NSString*) testString1 andInput:(NSString*)testString2 {
NSLog(@"%@ %@", testString1, testString2);
}
- (void)executeSelector:(SEL)func fromObject:(id)object {
[object performSelector:func];
}
- (void)runSelector {
NSString* string1 = @"Hello ";
NSString* string2 = @"World";
[self executeSelector:@selector(testWithInput:andInput:) fromObject:self];
}
但是,如何在 runSelector 函式中指定 string1 和 string2 需要作為選擇器的引數傳入?
我想我可以將引數作為一組單獨的引數傳遞給執行選擇器——但這感覺很亂。有沒有更簡潔的方法?
我在 StackOverflow(和其他地方)上做了一些研究——但要么答案不太正確,要么我不能完全理解。
如何將@selector 作為引數傳遞?
如何將引數傳遞給選擇器?
Objective-C:使用多個引數呼叫選擇器
實際上,我很舒服地將引數傳遞給選擇器 - 選擇器本身就是一個我有問題的引數。
uj5u.com熱心網友回復:
您需要為引數添加引數。您設計的示例將適用于以下更改:
- (void) testWithInput:(NSString*) testString1 andInput:(NSString*)testString2 {
NSLog(@"%@ %@", testString1, testString2);
}
- (void)executeSelector:(SEL)func fromObject:(id)object withString1:(NSString *)string1 andString2:(NSString *)string2 {
// This doesn't scale. Two arguments is as far as you can go using `performSelector`.
[object performSelector:func withObject:string1 withObject:string2];
}
- (void)runSelector {
NSString* string1 = @"Hello ";
NSString* string2 = @"World";
[self executeSelector:@selector(testWithInput:andInput:) fromObject:self withString1:string1 andString2:string2];
}
由于不清楚您實際要完成什么,因此除了建議使用塊可能是更好的選擇之外,很難就更好的解決方案提供任何進一步的建議。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/537571.html
標籤:目标-c选择器
