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

移动开发 iOS
我建议还是养成良好的import习惯,不要偷懒都把import放在h文件中,无论参与的项目大小,养成良好的编程习惯非常重要。

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

这是因为h文件在修改后,所有import该h文件的所有文件必须重 新build,因此,如果把#import写在h文件中,import该h文件的文件也就会产生不必要的编译,增加编译时间,特别是在项目文件多的情况 下。想象一下,如果只是修改一个h文件而导致上百个文件不必要的编译,那是一件多么让人纠结的事情。。。

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

什么时候用@class这种方式声明比#import好呢?

stackoverflow上的高手们给了不少建议:

Randy Marsh:

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

  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.

 

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.

 

最后,我建议还是养成良好的import习惯,不要偷懒都把import放在h文件中,无论参与的项目大小,养成良好的编程习惯非常重要。

责任编辑:冰凝儿
相关推荐

2011-08-08 14:13:47

iPhone XML NSXMLParse

2010-03-16 15:23:32

java动态载入

2020-02-21 17:33:17

SparkKafka数据

2011-03-03 10:26:04

Pureftpd

2021-05-27 10:57:01

TCP定时器网络协议

2022-03-24 23:04:37

linux静态库动态库

2009-06-25 13:43:00

Buffalo AJA

2010-10-21 16:24:18

sql server升

2010-08-06 09:38:11

Flex读取XML

2023-03-29 13:06:36

2010-09-07 11:09:59

2024-03-29 11:33:23

转换[]bytestring

2011-06-16 10:02:08

JAVA静态载入

2009-09-08 15:22:20

Spring依赖注入

2011-04-02 09:48:38

深拷贝

2010-07-15 14:38:55

Perl eval函数

2016-11-07 09:02:02

Malloc内存syscall

2010-08-03 13:27:04

FlexBuilder

2024-02-04 09:24:45

MyBatisSQL语句Spring

2010-10-20 15:48:56

SQL Server许
点赞
收藏

51CTO技术栈公众号