[英]Properties in Objective C (readwrite for self and readonly for others)
[英]Objective-C : (private / public properties) making a property readonly for outside class calls and readwrite for self calls
您是否知道一种方法可以为外部调用创建一个属性readonly并为内部调用进行readwrite?
我以前读过很多东西
在.h
@property(nonatomic, readonly) NSDate* theDate;
在他们中
@interface TheClassName()
@property(nonatomic, retain) NSDate* theDate;
@end
但是在编译.m时,这会引发警告“TheClassName类继续中的属性theDate属性与类TheClassName属性不匹配”。
无论如何,它似乎工作(可以阅读,但不能从课外设置,可以从内部做两个)但我应该错过somehting以避免警告。 或者,如果你知道更好的方法来做到这一点......
在你的.h:
@property(nonatomic, retain, readonly) NSDate* theDate;
在你的.m:
@interface TheClassName()
@property(nonatomic, retain, readwrite) NSDate* theDate;
@end
如果您转向ARC,这个问题基本上已经消除。 您将在标头中声明一次,而不是两个属性声明。
@property(nonatomic, readonly) NSDate* theDate;
然后在类扩展中,只需声明一个__strong实例变量。
@interface TheClassName()
{
__strong NSDate* _theDate;
}
@end
并在实现中适当地合成它们
@implementation TheClassName
@synthesize theDate = _theDate;
现在您可以设置实例变量。
_theDate = [NSDate date];
ARC将神奇地将适当的保留/释放功能内联到您的代码中,以将其视为强/保留变量。 这样做的优点是比旧样式(保留)属性更快,ARC在编译时内联保留/释放代码。
如果属性由变量支持,则该类的变量是默认的类内部读写。 将属性设置为只读,您的设计目标将得到满足。 在类中,请参考变量而不预先self.
。
在.m中,你不应该再次放置@property。 不过,我不确定它会产生什么影响。 你的意思是使用@synthesize吗?
请注意,无论如何,无论是对外部世界的只读,都将在类实现中读/写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.