2010-12-20 112 views
35
id parent; 
SEL selector; 

// lot's of code... 

if ([parent respondsToSelector:selector]) { 

} 
else { 
    // This doesn't work: 
    NSString *errorMessage = [NSString stringWithFormat:@"%@ in class %@ doesn't exist!", selector, parent]; 
} 

如何將「SEL」和「id」轉換爲字符串?如何把「SEL」和「id」轉換爲NSString?

回答

80

呼叫NSStringFromSelector()通過你選擇作爲它的參數,以獲得選擇的字符串,並使用[parent class]parent對象的類:

NSString *errorMessage = [NSString stringWithFormat:@"%@ in class %@ doesn't exist!", 
    NSStringFromSelector(selector), 
    [parent class]]; 
+13

相反的方式是: SEL aSelector = NSSelectorFromString(@ 「tapMeAction:」) ; – neoneye 2012-07-24 15:55:41

+0

只是想指出「@%s」,_ cmd用於工作(現在仍然如此),但現在發佈警告。這似乎是正確的方式 – 2012-08-07 17:34:18

+1

注 - 由'NSStringFromSelector'返回的字符串格式就是選擇器,例如。 '@ 「的setTitle:」'。即它沒有'@selector(〜)'包裝等。 – 2013-12-14 16:25:15