Objective-C: How do you access parent properties from subclasses?

后端 未结 5 1084
失恋的感觉
失恋的感觉 2020-12-04 16:28

If I have this class defined, how do I access the someObject property in subclasses without compiler errors?

@interface MyBaseClass
  // someObj         


        
5条回答
  •  误落风尘
    2020-12-04 16:59

    that's how you access them. how you declare them is what's biting you:

    @interface MyBaseClass : NSObject
    @property (nonatomic, readwrite, retain) NSObject *someObject;
    @end
    

    this is the normal way to declare a new objc class.

    by adding the parentheses (instead of declaring the superclass - NSObject in this case), you have declared a class extension, which is probably not visible to the subclass (via inclusion).

    you will probably never need to declare a root class in objc:

    @interface MyBaseClass // << superclass omitted
    @property (nonatomic, readwrite, retain) NSObject *someObject;
    @end
    

    NSObject (or a subclass of, assuming you're target apple's systems) should be the base class unless you're very experienced and know what a root class is for.

    class extensions are often used to 'simulate' private interfaces. by simulate, the compiler doesn't enforce this, as it would be enforced in other languages. for example, all messages are still dynamic, although the subclass may (unknowingly) override methods in your extensions, if declared with the same selector.

提交回复
热议问题