標籤:blog http io os ar 使用 for strong sp
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]init];
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];
}
注意:updated at 20120606
1.如果使用了ARC會產生“performSelector may cause a leak because its selector is unknown”警告
2.這種方式當傳入一個不符合約定的訊息時會繼續運行並不報錯。例如應該傳入2個參數,但只傳入1個參數。或傳入了3個參數,第三個參數不會被初始化。
還有一種調用其他Class Function的方法是,但是不能有參數,我們這裡假設沒有參數,那麼就可以這樣
[mfs customSelector];
完整的代碼:
@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
--EOF--
Objective-C中一種訊息處理方法performSelector