简体   繁体   English

Objective-C :(私有/公共属性)为外部类调用创建一个readonly属性,为self调用创建readwrite

[英]Objective-C : (private / public properties) making a property readonly for outside class calls and readwrite for self calls

Would you know a way to make a property readonly for outside calls and readwrite for inside calls ? 您是否知道一种方法可以为外部调用创建一个属性readonly并为内部调用进行readwrite?

I've read times ago somthing that seemed like 我以前读过很多东西

In the .h 在.h

@property(nonatomic, readonly) NSDate* theDate;

In the .m 在他们中

@interface TheClassName()
@property(nonatomic, retain) NSDate* theDate;
@end

but this raises a warning when compiling the .m "Property theDate attribute in TheClassName class continuation does not match class TheClassName property". 但是在编译.m时,这会引发警告“TheClassName类继续中的属性theDate属性与类TheClassName属性不匹配”。

Anyway, it seems to work (can read but not set from outside the class, can do both from inside) but I should have missed somehting to avoid the warning. 无论如何,它似乎工作(可以阅读,但不能从课外设置,可以从内部做两个)但我应该错过somehting以避免警告。 Or if you know a better way to do this... 或者,如果你知道更好的方法来做到这一点......

In your .h: 在你的.h:

@property(nonatomic, retain, readonly) NSDate* theDate;

In your .m: 在你的.m:

@interface TheClassName()
@property(nonatomic, retain, readwrite) NSDate* theDate;
@end

This issue is largely eliminated if you're moving to ARC. 如果您转向ARC,这个问题基本上已经消除。 Instead of two property declarations, you'd declare it once in the header. 您将在标头中声明一次,而不是两个属性声明。

@property(nonatomic, readonly) NSDate* theDate;

And then in the class extension, simply declare a __strong instance variable. 然后在类扩展中,只需声明一个__strong实例变量。

@interface TheClassName()
{
    __strong NSDate* _theDate;
}
@end

And synthesize them appropriately in the implementation 并在实现中适当地合成它们

@implementation TheClassName
@synthesize theDate = _theDate;

Now you can set the instance variable. 现在您可以设置实例变量。

_theDate = [NSDate date];

And ARC will magically inline the appropriate retain/release functionality into your code to treat it as a strong/retained variable. ARC将神奇地将适当的保留/释放功能内联到您的代码中,以将其视为强/保留变量。 This has the advantage of being faster than the old style (retain) properties as well as ARC inlines the retain/release code at compile time. 这样做的优点是比旧样式(保留)属性更快,ARC在编译时内联保留/释放代码。

If the property is backed by a variable, the variable is read-write from inside the class be default. 如果属性由变量支持,则该类的变量是默认的类内部读写。 Make the property read-only, and your design goal will be met. 将属性设置为只读,您的设计目标将得到满足。 Inside the class, refer to the variable without prepending self. 在类中,请参考变量而不预先self. .

In the .m, you shouldn't put @property again. 在.m中,你不应该再次放置@property。 I'm not sure what effect that has, though. 不过,我不确定它会产生什么影响。 Did you mean to use @synthesize? 你的意思是使用@synthesize吗?

Note that theDate will be read/write inside the class implementation anyway, regardless of being readonly to the outside world. 请注意,无论如何,无论是对外部世界的只读,都将在类实现中读/写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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