ios中@class和 #import,两种方式的讨论

 

ios中@class和 #import,两种方式的讨论

2012-05-28 08:57  269人阅读  评论(0)  收藏  举报

不少刚开始学习iOS开发的同窗可能在看别人的代码的时候会发现有部分#import操做写在m文件中,而h文件仅仅使用@class进行声明,不由纳闷起来,为何不直接把#import放到h文件中呢? ios

这是由于h文件在修改后,全部import该h文件的全部文件必须重 新build,所以,若是把#import写在h文件中,import该h文件的文件也就会产生没必要要的编译,增长编译时间,特别是在项目文件多的状况 下。想象一下,若是只是修改一个h文件而致使上百个文件没必要要的编译,那是一件多么让人纠结的事情。。。 编程

对于@class只是告诉编译器有这个class,请不要报错或警告,所以不会给编译形成影响。 dom

何时用@class这种方式声明比#import好呢? ide

stackoverflow上的高手们给了很多建议: 学习

Randy Marsh: ui

When I develop, I have only three things in mind that never cause me any problems. spa

  1. Import super classes
  2. Import parent classes (when you have children and parents)
  3. 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. .net

 

Justin: blog

Simple answer: You #import or #include when there is a physical dependency. Otherwise, you use forward declarations (@class MONClass ,struct MONStruct , @protocol MONProtocol ). three

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.

最后,我建议仍是养成良好的import习惯,不要偷懒都把import放在h文件中,不管参与的项目大小,养成良好的编程习惯很是重要。
相关文章
相关标签/搜索