Objective-C: forward class declaration

I am writing a multi-user application that uses a class called RootViewController to switch between views.

In my MyAppDelegate header MyAppDelegate I create an instance of RootViewController called RootViewController . I've seen examples of such where the @class directive is used as a "direct class declaration", but I'm not quite sure what that means or does.

 #import <UIKit/UIKit.h> @class RootViewController; @interface MyAppDelegate . . . 
+45
c-preprocessor objective-c forward-declaration
Mar 04 2018-11-11T00:
source share
1 answer

It basically tells the compiler that the RootViewController class exists without specifying exactly how it looks (i.e. its methods, properties, etc.). You can use this to write code that includes variables like RootViewController without having to include a full class declaration.

This is especially useful when resolving circular dependencies - for example, where say ClassA has a member of type ClassB* , and ClassB has a member of type ClassA* . You need to declare ClassB before you can use it in ClassA , but you will also need ClassA before you can use it in ClassB . Advanced declarations allow you to overcome this by telling ClassA that ClassB exists, without ClassB's actually specifying the full specification.

Another reason you tend to find many advanced declarations is that some people accept a convention about starting class declarations if they absolutely should not include a full declaration. I don’t quite remember, but maybe something that Apple recommends in it Objective-C style guidelines.

Continuing my example above, if your ClassA and ClassB declarations are in the ClassA.h and ClassB.h respectively, you will need #import depending on which one to use its declaration in another class. Using a direct declaration means that you #import not needed, which makes the code more beautiful (especially after you start compiling quite a few classes, each of which will need `#import where it is used), and increases compilation of performance by minimizing the amount of code that is compiled p must be considered when compiling any given file.

On the sidelines, although the question concerns only direct declarations in Objective-C, all subsequent comments are equally applicable to coding in C and C ++ (and, possibly, in many other languages), which also support declarations in the forward direction and usually use it for the same purpose.

+96
Mar 04 2018-11-11T00:
source share



All Articles