簡體   English   中英

Objective-C:如何執行performSelector:@selector?

[英]Objective-C: How to perform a performSelector:@selector?

好吧,我正在創建一個自定義 SEL,例如:

NSArray *tableArray = [NSArray arrayWithObjects:@"aaa", @"bbb", nil];
for ( NSString *table in tableArray ){
    SEL customSelector = NSSelectorFromString([NSString stringWithFormat:@"abcWith%@", table]);
    [self performSelector:customSelector withObject:0];
}

我收到一個錯誤:由於未捕獲的異常'NSInvalidArgumentException'而終止應用程序,原因:'-[Sync aaaWithaaa]:無法識別的選擇器發送到實例

但如果我用真正的方法名稱運行它,它就會工作!

[self performSelector:@selector(aaaWithaaa:) withObject:0];

怎么解決呢?

您已經從字符串創建了選擇器 - 將其傳遞給 performSelector: 方法:

[self performSelector:customSelector withObject:0];

編輯:請注意,如果您的方法采用參數,那么在從中創建選擇器時必須使用冒號:

// Note that you may need colon here:
[NSString stringWithFormat:@"abcWith%@:", table]
NSArray *tableArray = [NSArray arrayWithObjects:@"aaa", @"bbb", nil];

for ( NSString *table in tableArray ){
     SEL customSelector = NSSelectorFromString([NSString stringWithFormat:@"abcWith%@:", table]);
     [self performSelector:customSelector withObject:0];
 }

關。

不同之處在於,使用@selector(aaaWithaaa:)傳遞的是方法名稱,而使用@selector(customSelector:)傳遞的是SEL 類型的變量(帶有一個備用冒號)。

相反,您只需要:

[self performSelector:customSelector withObject:0];

另一個區別是你在末尾了一個冒號的字符串,但是你的stringWithFormat:沒有。 這一點很重要; 這意味着該方法需要一個參數。 如果你的方法有一個參數,它需要在那里,即

[NSString stringWithFormat:@"abcWith%@:", table]
- (id)performSelector:(SEL)aSelector withObject:(id)anObject

第一個參數是SEL類型。

SEL customSelector = NSSelectorFromString([NSString stringWithFormat:@"abcWith%@", table]);
[self performSelector:customSelector withObject:0];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM