2014-03-13 37 views
38

随着XCode 5.1,出现一个新的警告。这让我明白了-显然 -我做错了什么。自动属性综合(@属性)和继承

想法是有一个对象(模型),它是从原始类继承的可变版本。这样的想法是要打开的是readonlyreadwrite

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

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

那些需要在单独的文件(就像两个普通班)的属性。

,并让这样的警告:

Auto property synthesis will not synthesize property 'name' because it is 'readwrite' but it will be synthesized 'readonly' via another property 

所以我想知道什么是做类似的东西正确的解决方案,如果它甚至有可能。如果需要编写访问器并避免使用自动合成等,请务必精确并通过文档或其他方式支持您的答案。

+0

我无法用给定的代码重现警告。 – Tim

+0

我做了,是的,你需要把它放在单独的文件中(创建两个类) – AncAinu

+0

任何我可以通过或忽略的标志摆脱这一点? –

回答

56

我建议明确综合你的MutableCar实现的属性。如:

@implementation MutableCar 

@synthesize name; 

@end 

铛这样就不会尝试使用autosynthesis

编辑:

如果你不想使用封装和其他原因,你需要访问从伊娃父类,那么你需要做的一点点付出更多的努力:

首先,汽车.h文件中保持不变(我加了printVar方法打印伊娃和财产):

@interface Car : NSObject 

- (void)printVar; 

@property (strong, readonly) NSString *name; 

@end 

现在的.m文件,我实现printVar方法并且还加入了类扩展告诉铛创建二传手:

// 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 

现在你可以创建你的MutableCar.h像以前一样:

@interface MutableCar : Car 

@property (strong, readwrite) NSString *name; 

@end 

和你MutableCar.m应该是这样的:

@implementation MutableCar 

@dynamic name; 

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

@end 

这样的父母上的_name ivar实际上是使用家长制定者编写的,您可以访问它。

+0

它意味着功能的任何区别还是会一样? – AncAinu

+0

使用后,它不是一个好的答案,它是准确的,并删除了警告,但它改变了它的工作方式,因为它在子类中创建了一个新的iVar,而不是使用父类的受保护的类。 – AncAinu

+0

@anc你能告诉我你的确切情况吗?你是否有一个特定的物业伊娃?这个案例应该可以工作,看看这个例子:https://gist.github.com/Reflejo/11c91b929bf021308b95 –