Reputation: 313
In a iOS app, I needed a property which is readonly for other classes but readwrite for self calls. So I followed this question and formed my code as,
In .h:
@interface TheClassName : NSObject {
NSString* str;
}
@property(nonatomic, retain, readonly) NSString* str;
@end
In .m:
@interface TheClassName()
@property(nonatomic, retain, readwrite) NSString* str;
@end
@implementation TheClassName
-(id)init {
if(self = [super init]) {
str = [[NSString alloc] initWithString:@"hello"];
}
return self;
}
@end
This procedure is valid also according to Apple Documentation. But I tried experimenting on my code and the problem started.
All I did is ignored the @interface part in the .m file with respect to Seva Alekseyev's answer here, but compiler showed no warning or error when I used it as str = [[NSString alloc] initWithString:@"hello"]
in the .m file !!
I mean, the property is set to be readonly
, so the statement should have produced an error, but it didn't. WHY??
NOTE: I am using Xcode 5.1.1
Upvotes: 1
Views: 787
Reputation: 122381
This code:
str = [[NSString alloc] initWithString:@"hello"];
doesn't call the property setter, it references the instance variable you defined directly:
@interface TheClassName : NSObject {
NSString* str;
}
and, by default, the backing instance variable will be called _str
, so you should remove that instance variable definition and refer to _str
directly (if you don't want to create a readwrite
version of the property). As it currently stands the property str
won't refer to the instance variable str
without explicitly using a @synthesize str = str;
statement.
Upvotes: 3