原文出自:http://blog.csdn.net/hopedark/article/details/7970370app
Objective-C中調用函數的方法是「消息傳遞」,這個和普通的函數調用的區別是,你能夠隨時對一個對象傳遞任何消息,而不須要在編譯的時候聲明這些方法。因此Objective-C能夠在runtime的時候傳遞消息。函數
主要用到:SEL和@selector,固然還有performSelectoroop
看例子:spa
先是三個函數:.net
- -(void)CallBack0
- {
- NSLog(@"CallBack0");
- }
-
- -(void)CallBack1:(int)a
- {
- NSLog(@"CallBack1:a=%i",a);
- }
-
- -(void)CallBack2:(int)a b:(int)b
- {
- NSLog(@"CallBack2:a=%i,b=%i",a,b);
- }
performSelector調用:orm
- [self performSelector:@selector(CallBack0)];
- [self performSelector:@selector(CallBack1:) withObject:1];
- [self performSelector:@selector(CallBack2:b:) withObject:1 withObject:2];
根據函數名動態調用:對象
- NSString *a=@"CallBack0";
- SEL faSelector=NSSelectorFromString(a);
- [self performSelector:faSelector];
-
- NSString *b=@"CallBack1:";
- SEL fbSelector=NSSelectorFromString(b);
- [self performSelector:fbSelector withObject:1];
-
- NSString *c=@"CallBack2:b:";
- SEL fcSelector=NSSelectorFromString(c);
- [self performSelector:fcSelector withObject:1 withObject:2];
這樣就能夠根據函數名調用函數啦!blog