iOS self 和 super 學習
有人問我 這個問題 回答錯了,題干大概是說 [self class] 和 [super class]打印結果 是不是一樣的.
我睜著眼睛說是不一樣的 .因為我明明記得 幾天前 做 DFS 獲取反射基類 用到了這塊
然 pia pia 打臉
運行一遍 先印證答案:
在 AppDelegate 里面:
NSLog(@" %@ %@ %@",[self class],[super class],[self superclass]);
打印結果:
2016-05-18 16:38:14.918 dailylife[34114:1143377] AppDelegate AppDelegate UIResponder
其實看出來大概的區別了
和臆想一樣的 是"[self superclass]" 大概以為 最終結果 相同的人 都以為 [super class] 是 [self superclass].
其實,在開發過程 我真的沒有 說因為這個問題出錯.
因為在寫 init 方法中 首先會考慮到 override (重用) 的問題 會先 寫 [super class] . 然后 你要實施的重用 寫在該行代碼的下邊.
如果當時 我考慮到這個實際運用情況 就不會答錯了,真心丟人.
這就是純理論 和 實戰 對于一問題 不同的詮釋吧.
那么現在討論一下 為什么 [self class] 和 [super class]打印的結果相同
self : 我的理解 就是 當前類的 對象的本身 , 那么 [self class] 就可理解 為 獲取當前對象的類. 英文解釋:"self refers to the object receiving a message in objective-C programming."
super : 網上 解釋 它是一個編譯器的指令符號,我個人現在的理解 它是一種系統級別的 回溯查找 一直找到根,返回的接受者是 [self class] ;英文解釋:"super is a flag that tells the compiler to search for the method implementation in a very different place. It begins in the superclass of the class that defines the method where super appears."
網上特意講了底層機制: 我就不貼代碼了
http://chun.tips/blog/2014/11/05/bao-gen-wen-di-objective[nil]c-runtime%281%29[nil]-self-and-super/
但是 我不認為 網上說的 或者詢問方式為類似 "Why does “[self class] == [super class]”?" "或者說 它們兩個相等" 之類的 .我只能說他們結果一致 在一定程度上可以替換 .
但是濫用 也是有后果的, 會出現一個閉環.
- (instancetype)initWithFrame:(CGRect)frame { self = [super initWithFrame:frame]; if(self){ //TODO: } return self; } - (instancetype)initWithFrame:(CGRect)frame { self = [self initWithFrame:frame]; if(self){ //TODO: } return self; } - (instancetype)initWithNew:(CGRect)frame { self = [self initWithFrame:frame];//super as well if(self){ //TODO: } return self; }
我這么寫,應該很容易看出來了吧,
第一種情況,通過 super 編譯指令開始回溯,如果還有重寫回溯重寫 然后繼續回溯 一直到基類.
第二段代碼 則是再次調用當前方法 然后陷入了死循環.(類似這種情況就不能濫用, 并且 我們知道 在 初始化方法里面 盡量不要用點語法 ,不一定什么時候 就造成循環引用, 當然我們知道有這個坑,自己有避免的機制也無所謂啦)
第三段代碼 我們看到 這個時候 方法名不一樣 initWithNew: 和 initWithFrame: ,所以 用super self 都行 ,self 也最終會走到 super 的方法. 大家也可以在工程里面寫這幾個方法 然后點擊進去,或者debug一下看看走的每一步.
學到什么程度 都會有不懂的問題,也許對別人很簡單,自己才會. 丟臉不要緊 只要敢去找回你的顏.
慢慢積累吧 日子長著呢
posted on 2016-05-18 19:46 ACM_Someone like you 閱讀(256) 評論(0) 收藏 舉報
浙公網安備 33010602011771號