Auto property synthesis (@property) and inheritance

后端 未结 1 1433
梦谈多话
梦谈多话 2020-12-23 16:54

With XCode 5.1, a new warning appears. It made me understand -obviously- that I was doing something wrong.

The idea was to have an object (a model) and it\'

相关标签:
1条回答
  • 2020-12-23 17:07

    I'd suggest to explicitly synthesize the property on your MutableCar implementation. As in:

    @implementation MutableCar
    
    @synthesize name;
    
    @end
    

    That way clang won't try to use autosynthesis

    Edit:

    If you don't want to use encapsulation and for other reason you need to access the ivar from the parent class, then you need to do a little bit more effort:

    First the Car .h file remains the same (I added a printVar method to print the ivar and property):

    @interface Car : NSObject
    
    - (void)printVar;
    
    @property (strong, readonly) NSString *name;
    
    @end
    

    Now on the .m file, I'm implementing the printVar method and also adding a class extension to tell clang to create the setter:

    // Private class extension, causes setName: to be created but not exposed.
    @interface Car ()
    
    @property (strong, readwrite) NSString *name;
    
    @end
    
    @implementation Car
    
    - (void)printVar
    {
        NSLog(@"<Car> Hello %@, ivar: %@", self.name, _name);
    }
    
    @end
    

    Now you can create your MutableCar.h as before:

    @interface MutableCar : Car
    
    @property (strong, readwrite) NSString *name;
    
    @end
    

    and your MutableCar.m should looks like this:

    @implementation MutableCar
    
    @dynamic name;
    
    - (void)printVar
    {
        [super printVar];
        NSLog(@"<MutableCar> Hello %@", self.name);
    }
    
    @end
    

    That way the _name ivar on the parent is actually written using the parent setter and you can access it.

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