【iOS學習筆記】Objective-C中根據函數名調用函數

原文出自:http://blog.csdn.net/hopedark/article/details/7970370app

 

Objective-C中調用函數的方法是「消息傳遞」,這個和普通的函數調用的區別是,你能夠隨時對一個對象傳遞任何消息,而不須要在編譯的時候聲明這些方法。因此Objective-C能夠在runtime的時候傳遞消息。函數

主要用到:SEL和@selector,固然還有performSelectoroop

看例子:spa

先是三個函數:.net

 

[cpp]  view plain copy
  1. -(void)CallBack0  
  2. {  
  3.     NSLog(@"CallBack0");  
  4. }  
  5.   
  6. -(void)CallBack1:(int)a  
  7. {  
  8.     NSLog(@"CallBack1:a=%i",a);  
  9. }  
  10.   
  11. -(void)CallBack2:(int)a b:(int)b  
  12. {  
  13.     NSLog(@"CallBack2:a=%i,b=%i",a,b);  
  14. }  


performSelector調用:orm

 

 

[cpp]  view plain copy
  1. [self performSelector:@selector(CallBack0)];  
  2. [self performSelector:@selector(CallBack1:) withObject:1];  
  3. [self performSelector:@selector(CallBack2:b:) withObject:1 withObject:2];  

 

 

根據函數名動態調用:對象

 

[cpp]  view plain copy
  1. NSString *a=@"CallBack0";  
  2. SEL faSelector=NSSelectorFromString(a);  
  3. [self performSelector:faSelector];  
  4.       
  5. NSString *b=@"CallBack1:";  
  6. SEL fbSelector=NSSelectorFromString(b);  
  7. [self performSelector:fbSelector withObject:1];  
  8.       
  9. NSString *c=@"CallBack2:b:";  
  10. SEL fcSelector=NSSelectorFromString(c);  
  11. [self performSelector:fcSelector withObject:1 withObject:2];  


這樣就能夠根據函數名調用函數啦!blog

相關文章
相關標籤/搜索