iOS開發之IMP和SEL(方法和類的反射)

2022-09-14 08:57:10 字數 992 閱讀 1310

1、sel:類方法的指標,相當於一種編號,區別與imp!

sel是通過表取對應關係的imp,進行方法的呼叫!

2、獲取sel和imp方法和呼叫:

sel methodsel =@selector(str:);

[self performselector:methodsel withobject:nil];//方法的呼叫

nslog(

@"===%p

",methodsel);

imp methodimp =[self methodforselector:methodsel];

methodimp();//方法的呼叫

nslog(

@"===%p

",methodimp);

- (void)str:(nsstring *)str
顯示結果:

3、通過反射獲取方法名(包括class):

nsstring *methodname =nsstringfromselector(methodsel);

nslog(

@"對映===%@

",methodname);

nsstring *classname = nsstringfromclass([father class

]); nslog(

@"對映===%@

",classname);

class fatherclass =nsclassfromstring(classname);

nslog(

@"對映===%@

",fatherclass);

顯示結果:

iOS中的SEl和IMP到底是什麼

sel 類成員方法的指標,但不同於c語言中的函式指標,函式指標直接儲存了方法的位址,但sel只是方法編號。imp 乙個函式指標,儲存了方法的位址 imp和sel關係 每乙個繼承於nsobject的類都能自動獲得runtime的支援。在這樣的乙個類中,有乙個isa指標,指向該類定義的資料結構體,這個結...

iOS中的SEl和IMP到底是什麼

sel 類成員方法的指標,但不同於c語言中的函式指標,函式指標直接儲存了方法的位址,但sel只是方法編號。imp 乙個函式指標,儲存了方法的位址 imp和sel關係 每乙個繼承於nsobject的類都能自動獲得runtime的支援。在這樣的乙個類中,有乙個isa指標,指向該類定義的資料結構體,這個結...

OC中description方法和sel

補充兩個知識點 一 description方法 description方法包括類方法和物件方法。nsobject 類所包含 一 基本知識 description 物件方法 使用nslog和 輸出某個物件時,會呼叫物件的 description 方法,並拿到返回值進行輸出。description 類方...