iOS開發(fā) 關于SEL的簡單總結(jié)
作者:佚名
SEL就是對方法的一種包裝。包裝的SEL類型數(shù)據(jù)它對應相應的方法地址,找到方法地址就可以調(diào)用方法。在內(nèi)存中每個類的方法都存儲在類對象中,每個方法都有一個與之對應的SEL類型的數(shù)據(jù),根據(jù)一個SEL數(shù)據(jù)就可以找到對應的方法地址,進而調(diào)用方法。
- @interface Person : NSObject
- + (void)test1;
- - (void)test2;
- @end
- // 根據(jù).h文件中定義的Person類和方法 執(zhí)行完這行代碼 在內(nèi)存中如下
- Person *person = [[Person alloc] init];
SEL就是對方法的一種包裝。包裝的SEL類型數(shù)據(jù)它對應相應的方法地址,找到方法地址就可以調(diào)用方法
1.方法的存儲位置
- 在內(nèi)存中每個類的方法都存儲在類對象中
- 每個方法都有一個與之對應的SEL類型的數(shù)據(jù)
- 根據(jù)一個SEL數(shù)據(jù)就可以找到對應的方法地址,進而調(diào)用方法
- SEL類型的定義: typedef struct objc_selector *SEL
2.SEL對象的創(chuàng)建
- SEL s1 = @selector(test1); // 將test1方法包裝成SEL對象
- SEL s2 = NSSelectorFromString(@"test1"); // 將一個字符串方法轉(zhuǎn)換成為SEL對象
3.SEL對象的其他用法
- // 將SEL對象轉(zhuǎn)換為NSString對象
- NSString *str = NSStringFromSelector(@selector(test));
- Person *p = [Person new];
- // 調(diào)用對象p的test方法
- [p performSelector:@selector(test)];
- /******************************* Person.h文件 **********************************/
- #import <Foundation/Foundation.h>
- @interface Person : NSObject
- - (void)test1;
- - (void)test2:(NSString *)str;
- @end
- /******************************* Person.m文件 **********************************/
- #import "Person.h"
- @implementation Person
- - (void)test1
- {
- NSLog(@"無參數(shù)的對象方法");
- }
- - (void)test2:(NSString *)str
- {
- NSLog(@"帶有參數(shù)的方法%@",str);
- }
- @end
- /******************************* main.m文件 **********************************/
- #import "Person.h"
- #import <Foundation/Foundation.h>
- /*
- 調(diào)用方法有兩種方式:
- 1.直接通過方法名來調(diào)用
- 2.間接的通過SEL數(shù)據(jù)來調(diào)用
- */
- int main(int argc, const char * argv[])
- {
- Person *person = [[Person alloc] init];
- // 1.執(zhí)行這行代碼的時候會把test2包裝成SEL類型的數(shù)據(jù)
- // 2.然后根據(jù)SEL數(shù)據(jù)找到對應的方法地址(比較耗性能但系統(tǒng)會有緩存)
- // 3.在根據(jù)方法地址調(diào)用對應的方法
- [person test1];
- // 將方法直接包裝成SEL數(shù)據(jù)類型來調(diào)用 withObject:傳入的參數(shù)
- [person performSelector:@selector(test1)];
- [person performSelector:@selector(test2:) withObject:@"傳入?yún)?shù)"];
- return 0;
- }
責任編輯:閆佳明
來源:
cnblogs