Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
536 views
in Technique[技术] by (71.8m points)

syntax - Objective-C: @class Directive before @interface?

What is the difference between these two class declarations? I don't understand why @class is utilized here. Thanks.

@class TestClass;

@interface TestClass: UIView {
    UIImage *image1;
    UIImage *image2;
}

and

@interface TestClass: UIView {
    UIImage *image1;
    UIImage *image2;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

@class exists to break circular dependencies. Say you have classes A and B.

@interface A:NSObject
- (B*)calculateMyBNess;
@end

@interface B:NSObject
- (A*)calculateMyANess;
@end

Chicken; meet Egg. This can never compile because A's interface depends on B being defined and vice-versa.

Thus, it can be fixed by using @class:

@class B;
@interface A:NSObject
- (B*)calculateMyBNess;
@end

@interface B:NSObject
- (A*)calculateMyANess;
@end

@class effectively tells the compiler that such a class exists somewhere and, thus, pointers declared to point to instances of said class are perfectly valid. However, you couldn't call a method on an instance reference whose type is only defined as an @class because there is no additional metadata available to the compiler (I can't remember if it reverts the call site to being evaluated as a call through id or not).

In your example, the @class is harmless, but entirely unnecessary.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...