Be A Final Tester

objective-C 中使用@Class和 #import区别

上一篇 / 下一篇  2011-03-08 11:07:30

We can import class declaration with #import:

#import "SomeClass.h" 

or declare with @class:

@classSomeClass; 

What's the difference and when we should use each of them?

 

Answer

"Import" links the header file it contains. Everything in the header, including property definitions, method declarations and any imports in the header are made available. Import provides the actual definitions to the linker.

@class by contrast just tells the linker not to complain it has no definition for a class. It is a "contract" that you will provide a definition for the class at another point.

Most often you use @class to prevent a circular import i.e. ClassA refers to ClassB so it imports ClassB.h in its own ClassA.h but ClassB also refers to ClassA so it imports ClassA.h in ClassB.h. Since the import statement imports the imports of a header, this causes the linker to enter an infinite loop.

Moving the import to the implementation file (ClassA.m) prevents this but then the linker won't recognize ClassB when it occurs in ClassA.h. The@class ClassB;directive tells the linker that you will provide the header for ClassB later before it is actually used in code.

当有两个类A,类B。在类A.h中#import类B.h。然后当我们写类B的时候,我们又需要用到类A的时候。使用类A.h包含在类B.h中,这样当在编译的时候,编译器就会重复、循环地在A.h 和B.h中来回的加载。此时,我们可以使用这样来避免出现这种情况。

在类A.h中,我们可以包含类B.h,但在类B.h中当我们需要使用类A时,我们可以使用@class A,这只是告诉编译器,你为类B提供了一个类A的定义,其他的都没做。这样就不会存在重复循环调用了。

其实,在类A.h中如果不会用到类B时,只是在A.m中用到类B时,你可以在A.m中#import B.h,只有当需要在类A.h中要用到类B时,才使用@class B.

/****************/http://heidianfeng.blog.163.com/blog/static/618434562010710102435778/

/*****/

二者的区别在于:

1.import会包含这个类的所有信息,包括实体变量和方法,而@class只是告诉编译器,其后面声明的名称是类的名称,至于这些类是如何定义的,暂时不用考虑,后面会再告诉你。

2.在头文件中, 一般只需要知道被引用的类的名称就可以了。 不需要知道其内部的实体变量和方法,所以在头文件中一般使用@class来声明这个名称是类的名称。 而在实现类里面,因为会用到这个引用类的内部的实体变量和方法,所以需要使用#import来包含这个被引用类的头文件。

3.在编译效率方面考虑,如果你有100个头文件都#import了同一个头文件,或者这些文件是依次引用的,如A–>B, B–>C, C–>D这样的引用关系。当最开始的那个头文件有变化的话,后面所有引用它的类都需要重新编译,如果你的类有很多的话,这将耗费大量的时间。而是用@class则不会。

4.如果有循环依赖关系,如:A–>B, B–>A这样的相互依赖关系,如果使用#import来相互包含,那么就会出现编译错误,如果使用@class在两个类的头文件中相互声明,则不会有编译错误出现。

所以,一般来说,@class是放在interface中的,只是为了在interface中引用这个类,把这个类作为一个类型来用的。 在实现这个接口的实现类中,如果需要引用这个类的实体变量或者方法之类的,还是需要import在@class中声明的类进来.

google_protectAndRun("render_ads.js::google_render_ad", google_handleError, google_render_ad);

 


TAG:

 

评分:0

我来说两句

love_yebin

love_yebin

难得清闲~最近很谋乱

日历

« 2024-05-02  
   1234
567891011
12131415161718
19202122232425
262728293031 

数据统计

  • 访问量: 19110
  • 日志数: 29
  • 建立时间: 2009-02-05
  • 更新时间: 2012-03-02

RSS订阅

Open Toolbar