In a iOS app, I needed a property which is . 。 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 part in the with respect to 's answer here , but compiler showed no warning or error when I used it as str = [[NSString alloc] initWithString:@"hello"]
in the !! 的答案的部分在这里 ,但是编译器没有显示警告或错误,当我用它作为str = [[NSString alloc] initWithString:@"hello"]
在 !!
I mean, the property is set to be readonly
, so the statement should have produced an error, but it didn't.
I am using Xcode 5.1.1 我使用的是Xcode 5.1.1
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.
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.