#import和@class之间有什么区别,我应该什么时候使用一个呢? [英] What's the difference between #import and @class, and when should I use one over the other?
问题描述
在过去的一个月里我一直在教自我Objective-C(我是一个Java头),我现在已经把大脑包裹了。有一件事,我现在困惑我:通过@class导入类和做一个#import有什么区别?
I've been teaching myself Objective-C over the past month or so (I'm a Java head) and I've got my brain wrapped around most of it now. One thing that's confusing me at the moment: What's the difference between importing a class via @class vs doing a #import?
一个比另一个更好,还是在某些情况下我需要使用一个而不是另一个?我目前只使用#import。
Is one better than another one, or do I need to use one instead of the other in certain cases? I've been using just #import so far.
推荐答案
#import
将整个头文件放入当前文件;还包括任何文件THAT文件 #import
。 @class,另一方面(当在一行上用一些类名称来使用时),只是告诉编译器嘿,你会很快看到一个新的令牌;它是一个类,所以这样对待它)。
#import
brings the entire header file in question into the current file; any files that THAT file #import
s are also included. @class, on the other hand (when used on a line by itself with some class names), just tells the compiler "Hey, you're going to see a new token soon; it's a class, so treat it that way).
当你有循环包含的潜力时,这是非常有用的;即Object1.h引用Object2,Object2.h引用Object1 。如果你 #import
两个文件到另一个,编译器可能会感到困惑,因为它试图 #import
Object1。 h,查看并查看Object2.h;它尝试 #import
Object2.h,并查看Object1.h等。
This is very useful when you've got the potential for 'circular includes'; ie, Object1.h makes reference to Object2, and Object2.h makes reference to Object1. If you #import
both files into the other, the compiler can get confused as it tries to #import
Object1.h, looks in it and sees Object2.h; it tries to #import
Object2.h, and sees Object1.h, etc.
另一方面,如果每个文件都有 @class Object1;
或 @class Object2;
,那么没有循环引用,只要确保实现<。c> c> #import 所需的头文件到您的实现(.m)文件。
If, on the other hand, each of those files has @class Object1;
or @class Object2;
, then there's no circular reference. Just be sure to actually #import
the required headers into your implementation (.m) files.
这篇关于#import和@class之间有什么区别,我应该什么时候使用一个呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!