对于XCode 5.1,会出现一个新的警告.这让我明白我做错了什么.

其 idea 是要有一个对象(一个模型)及其从原始类继承的可变版本.所以我们的 idea 是开一个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

所以我想知道,如果可能的话,做类似的事情的正确解决方案是什么.如果需要编写访问器,避免使用自动合成等,请精确,并用文档或任何东西支持您的答案.

推荐答案

我建议在MutableCar实现中显式地综合属性.例如:

@implementation MutableCar

@synthesize name;

@end

这样,clang就不会try 使用autosynthesis

编辑:

如果您不想使用封装,并且出于其他原因需要从父类访问ivar,那么您需要做更多的工作:

首先是汽车.h文件保持不变(我添加了一个printVar方法来打印ivar和属性):

@interface Car : NSObject

- (void)printVar;

@property (strong, readonly) NSString *name;

@end

现在开始.m文件,我正在实现printVar方法,还添加了一个类扩展来告诉clang创建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

现在你可以创建你的可变汽车了.h一如既往:

@interface MutableCar : Car

@property (strong, readwrite) NSString *name;

@end

还有你那辆易变的车.m应该是这样的:

@implementation MutableCar

@dynamic name;

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

@end

这样,父对象上的_nameivar实际上是使用父对象setter编写的,您可以访问它.

Objective-c相关问答推荐

如何使用 iOS 7 SpriteKit 粒子向非游戏的 iOS 应用程序添加粒子效果?

NSDateFormatter,我做错了什么还是这是一个错误?

Objective-C 中的实例变量是否默认设置为 nil?

iPhone 可达性判断

等到多个网络请求都执行完毕 - 包括它们的完成块

多个 WKWebView 之间的 Cookie 共享

将类作为参数传递?

iOS 7 / Xcode 5:以编程方式访问设备启动图像

NSLocalizedString 格式

碰撞技术如何运作?

对 nil 对象进行快速枚举

当单元格全屏时,为什么 UICollectionView 会记录错误?

如何测试生产推送通知?

使用情节提要的条件转场

更改后退导航栏按钮的字体

如何在 Objective-C 中将 NSString 解析为 BOOL?

以编程方式查找 iphone 的语言环境货币

BOOL到 NSString

有没有办法在用户已经在 iOS 上拒绝相机访问权限后向他们询问?

如何在 Objective-c 中将数组声明为常量?