摘要: Objective-C中調用函數的方法是訊息傳遞,這個和普通的函數調用的區別是,你可以隨時對一個對象傳遞任何訊息,而不需要在編譯的時候聲明這些方法。所以Objective-C可以在runtime的時候傳遞人和訊息。首先介紹兩個方法。
Objective-C中調用函數的方法是“訊息傳遞”,這個和普通的函數調用的區別是,你可以隨時對一個對象傳遞任何訊息,而不需要在編譯的時候聲明這些方法。所以Objective-C可以在runtime的時候傳遞人和訊息。
首先介紹兩個方法 SEL和@selector
根據AppleObjective-C Runtime Reference官方文檔這個傳遞訊息的函數就是 id objc_msgSend(id theReceiver, SEL theSelector, …)
theReceiver是接受訊息的物件類型是id,theSelector是訊息名稱類型是SEL。下邊代碼我們來看看如何來產生一個SEL,如果傳遞訊息。
首先建立一個簡單的函數
- (void) fooNoInputs {
NSLog(@"Does nothing");
}
然後調用它
[self performSelector:@selector(fooNoInputs)];
第二個實驗看看如何在訊息中傳遞參數
我們建立一個有input參數的函數
- (void) fooOneIput:(NSString*) first {
NSLog(@"Logs %@", first);
}
然後調用它
[self performSelector:@selector(fooOneInput:) withObject:@"first"];
第三個實驗更多的參數
- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second {
NSLog(@"Logs %@ then %@", first, second);
}
然後調用它
[self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first"withObject:@"second"];
第四個實驗如何建立動態函數,然後調用他們?我們需要建立一個selector
SEL myTestSelector = @selector(myTest:);
並且我們調用的函數在另外一個Class內
- (void)abcWithAAA: (NSNumber *)number {
int primaryKey = [number intValue];
NSLog("%i", primaryKey);
}
MethodForSelectors * mfs = [MethodForSelectors alloc];
NSArray *Arrays = [NSArray arrayWithObjects:@"AAA", @"BBB", nil];
for ( NSString *array in Arrays ){
SEL customSelector = NSSelectorFromString([NSStringstringWithFormat:@"abcWith%@:", array]);
mfs = [[MethodForSelectors alloc] performSelector:customSelector withObject:0];
}
完整的代碼:
@implementation ClassForSelectors
- (void) fooNoInputs {
NSLog(@"Does nothing");
}
- (void) fooOneIput:(NSString*) first {
NSLog(@"Logs %@", first);
}
- (void) fooFirstInput:(NSString*) first secondInput:(NSString*) second {
NSLog(@"Logs %@ then %@", first, second);
}
- (NSArray *)abcWithAAA: (NSNumber *)number {
int primaryKey = [number intValue];
NSLog("%i", primaryKey);
}
- (void) performMethodsViaSelectors {
[self performSelector:@selector(fooNoInputs)];
[self performSelector:@selector(fooOneInput:) withObject:@"first"];
[self performSelector:@selector(fooFirstInput:secondInput:) withObject:@"first"withObject:@"second"];
}
- (void) performDynamicMethodsViaSelectors {
MethodForSelectors * mfs = [MethodForSelectors alloc];
NSArray *Arrays = [NSArray arrayWithObjects:@"AAA", @"BBB", nil];
for ( NSString *array in Arrays ){
SEL customSelector = NSSelectorFromString([NSStringstringWithFormat:@"abcWith%@:", array]);
mfs = [[MethodForSelectors alloc] performSelector:customSelector withObject:0];
}
}
@end
@implementation MethodForSelectors
- (void)abcWithAAA: (NSNumber *)number {
NSLog("%i", number);
}
@end