简体   繁体   中英

the effect of readonly attribute to Objective-C @property directive

here is my situation, I declare an objective-c class as below:

@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!
}

I tag the "path" & "childItems" as readonly property, the compiler complain that "_childItems" identifier undeclared, it seems that I can't use "-(NSArray*)childItem" as the "childItem" property 's getter function(I change the function name, everything goes fine), why? I understand a "readonly" attr make the xcode omit a property's setter function, but what effect to the getter function?

From Apple documentation: "If you implement both a getter and a setter for a readwrite property, or a getter for a readonly property , the compiler will assume that you are taking control over the property implementation and won't synthesize an instance variable automatically."

A common approach is to put the "readonly" property in the header and a duplicate property definition inside a class extension without the "readonly" attribute.

Xcode complains because the Problem with your code is that a property is not automatically synthesized if you implement all required accessor methods, which for your read only property would be simply implementing the getter.

Add the following after @implementation:

@synthesize childItems = _childItems;

and the error should go away...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM