iOS中@class和 #import,兩種方式的討論
很多剛開始學(xué)習(xí)iOS開發(fā)的同學(xué)可能在看別人的代碼的時(shí)候會(huì)發(fā)現(xiàn)有部分#import操作寫在m文件中,而h文件僅僅使用@class進(jìn)行聲明,不禁納悶起來,為什么不直接把#import放到h文件中呢?
這是因?yàn)閔文件在修改后,所有import該h文件的所有文件必須重 新build,因此,如果把#import寫在h文件中,import該h文件的文件也就會(huì)產(chǎn)生不必要的編譯,增加編譯時(shí)間,特別是在項(xiàng)目文件多的情況 下。想象一下,如果只是修改一個(gè)h文件而導(dǎo)致上百個(gè)文件不必要的編譯,那是一件多么讓人糾結(jié)的事情。。。
對(duì)于@class只是告訴編譯器有這個(gè)class,請(qǐng)不要報(bào)錯(cuò)或警告,因此不會(huì)給編譯造成影響。
什么時(shí)候用@class這種方式聲明比#import好呢?
stackoverflow上的高手們給了不少建議:
Randy Marsh:
When I develop, I have only three things in mind that never cause me any problems.
- Import super classes
- Import parent classes (when you have children and parents)
- Import classes outside your project (like in frameworks and libraries)
For all other classes (subclasses and child classes in my project self), I declare them via forward-class.
Justin:
Simple answer: You #import or #include when there is a physical dependency. Otherwise, you use forward declarations (@class MONClass ,struct MONStruct , @protocol MONProtocol ).
Here are some common examples of physical dependence:
- Any C or C++ value (a pointer or reference is not a physical dependency). If you have aCGPoint as an ivar or property, the compiler will need to see the declaration ofCGPoint .
- Your superclass.
- A method you use.
最后,我建議還是養(yǎng)成良好的import習(xí)慣,不要偷懶都把import放在h文件中,無論參與的項(xiàng)目大小,養(yǎng)成良好的編程習(xí)慣非常重要。