when and where to put @class declarations

后端 未结 2 1036
南方客
南方客 2021-01-19 11:57

I am working on a project with several custom classes. I have a CardModel (NSObject) that has some integer properties to hold data, and a Deck (NS

相关标签:
2条回答
  • 2021-01-19 12:03

    You use it in the .h to inform it about a custom class without including the .h for the custom class.

    Example: Two custom classes: Car and Wheel

    Car.h
    ----------------
    @interface Car : NSObject {
    }
    - (void)addWheel:(Wheel*)newWheel;
    @end
    

    Car.h doesn't know about the class 'Wheel' so it would throw an error so you could import the Wheel.h like so:

    Car.h
    ----------------
    #import "Wheel.h"
    
    @interface Car : NSObject {
    }
    - (void)addWheel:(Wheel*)newWheel;
    @end
    

    BUT you dont need to do this either. Car.h doesn't need to know anything about the Wheel class, it just needs to know it exists. So what you use is the @class to just say that "Hey, this class exists. Take my word for it."

    Car.h
    ----------------
    @class Wheel;
    
    @interface Car : NSObject {
    }
    - (void)addWheel:(Wheel*)newWheel;
    @end
    

    Then inside of the Car.m, when you actually need to know about the Wheel class (properties, methods, etc) you should import the Wheel.h there.

    0 讨论(0)
  • 2021-01-19 12:23

    The @class directive is used when you need a header to know about a class but you don't want to import the class's header file; e.g., when you need to avoid circular dependencies.

    0 讨论(0)
提交回复
热议问题