【问题标题】:the effect of readonly attribute to Objective-C @property directive只读属性对 Objective-C @property 指令的影响
【发布时间】:2015-02-05 13:57:05
【问题描述】:

这是我的情况,我声明一个objective-c类如下:

@interface FileItem : NSObject
@property (nonatomic, strong, readonly) NSString *path;
@property (nonatomic, strong, readonly) NSArray* childItems;
- (id)initWithPath:(NSString*)path;
@end

@implementation LCDFileItem

- (id)initWithPath:(NSString*)path {
    self = [super init];
    if (self) {
        _path = path;
    }
    return self;
}

- (NSArray*)childItems {
    if (!_childItems) {         // error, _childItems undeclared!
        NSError *error;
        NSMutableArray *items = [[NSMutableArray alloc] init];
        _childItems = items;    // error, _childItems undeclared!
    }
    return _childItems;         // error, _childItems undeclared!
}

我将“path”和“childItems”标记为只读属性,编译器抱怨“_childItems”标识符未声明,似乎我不能使用“-(NSArray*)childItem”作为“childItem”属性' s getter 函数(我改了函数名,一切正常),为什么? 我理解“只读”属性使 xcode 省略了属性的 setter 函数,但是对 getter 函数有什么影响?

【问题讨论】:

    标签: objective-c xcode properties


    【解决方案1】:

    来自 Apple 文档:“如果您为读写属性实现 getter 和 setter,或为只读属性实现 getter,编译器将假定您正在控制属性实现并且不会自动合成实例变量。”

    一种常见的方法是将“readonly”属性放在标题中,将重复的属性定义放在类扩展中没有“readonly”属性。

    【讨论】:

      【解决方案2】:

      Xcode 抱怨,因为您的代码的问题是属性不是自动合成的实施吸气剂。

      在@implementation之后添加以下内容:

      @synthesize childItems = _childItems;
      

      错误应该会消失...

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-06-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-08-14
        • 1970-01-01
        • 1970-01-01
        • 2014-03-06
        相关资源
        最近更新 更多