Reputation: 313
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?
Upvotes: 0
Views: 428
Reputation: 31016
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.
Upvotes: 2
Reputation: 455
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...
Upvotes: 1