@class与#import的区别

按我个人的理解,class与import的区分主要是为了解决引用死锁的问题。

stackOverFlow上有个人是这样解释这个问题的:

If you see this warning:

warning: receiver 'myCoolClass' is a forward class and corresponding @interface may not exist

you need to #import the file, but you can do that in your implementation file (.m), and use the @class declaration in your header file.

@class does not (usually) remove the need to #import files, it just moves the requirement down closer to where the information is useful.

For Example

If you say @class myCoolClass, the compiler knows that it may see something like:

myCoolClass *myObject;

It doesn't have to worry about anything other than myCoolClass is a valid class, and it should reserve room for a pointer to it (really, just a pointer). Thus, in your header, @class suffices 90% of the time.

However, if you ever need to create or access myObject's members, you'll need to let the compiler know what those methods are. At this point (presumably in your implementation file), you'll need to #import "myCoolClass.h", to tell the compiler additional information beyond just "this is a class".

先看看什么情况下应该用@class


1.   file1.h 

 
@class class2
 
@interface class1
{
    class2* class2Object;
}
 
@end
 
@interface class2
{
    class1* class1Object;
}
@end



2. class1.h中引入class2.h头文件
 
#import "class2.h"
@interface class1
{
    class2* class2Object;
}
 
@end
 


class2.h中引入class1.h头文件
 
#import "class1.h"
@interface class2
{
    class1* class1Object;
}
@end
 

这种情况会导致引用死锁,所以应该用forward declaration

class1.h, 在class1.m中添加 #import "class2.h"
 
@class class2;
@interface class1
{
    class2* class2Object;
}
 
@end
 
 


class2.h,在class2.m中添加#import "class2.h"
 
@class class1;
@interface class2
{
    class1* class1Object;
}
@end
 


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值