Why are instance variables defined in the header file in Objective-C

前端 未结 6 1496
一个人的身影
一个人的身影 2021-01-12 22:36

I can understand defining the functions in the @interface of the header file, but why the instance variables? Shouldn\'t the instance variables be private, only accessible

6条回答
  •  终归单人心
    2021-01-12 22:50

    The reason is so it can calculate offsets of variables for subclasses.

    @interface Bird : NSObject {
        int wingspan;
    }
    @end
    @interface Penguin : Bird {
        NSPoint nestLocation;
        Penguin *mate;
    }
    @end
    

    Without knowing the structure of the "Bird" class, the "Penguin" class can't calculate the offset of its fields from the beginning of the structure. The penguin structure looks kind of like this:

    struct Penguin {
        int refcount; // from NSObject
        int wingspan; // from Bird
        NSPoint nestLocation; // from Penguin
        Penguin *mate; // from Penguin
    }
    

    This has a side effect: if you change the size of a class in a library, you break all the subclasses in apps that link to that library. The new properties work around this problem.

提交回复
热议问题