当未存储对值的引用时,应使用哪些 @property 属性?
我有一个属性:
@property(readwrite, ?????) NSDate *selectedDate;
访问器如下所示:
NSCalendar _calendar;
NSDateComponents _selectedDateComponents;
@dynamic selectedDate;
- (void)setSelectedDate:(NSDate *)newDate
{
@synchronized(_selectedDateComponents)
{
if (!newDate) return;
[_selectedDateComponents release];
int requiredComponents = NSDayDateComponent | NSMonthDateComponent | NSYearDateComponents;
_selectedDateComponents = [[_calendar components: requiredComponents fromDate:newDate] retain];
}
}
- (NSDate *)selectedDate
{
@synchronized(_selectedDateComponents)
{
if (!_selectedDateComponents) return nil;
return [_calendar dateFromComponents:_selectedDateComponents];
}
}
该类不保留对发送到设置器的对象的引用。 retain
、copy
或 assign
似乎都不合适。我喜欢将此功能封装为属性,但属性可能不合适。
你的看法是什么?
I have a property:
@property(readwrite, ?????) NSDate *selectedDate;
The accessors are like so:
NSCalendar _calendar;
NSDateComponents _selectedDateComponents;
@dynamic selectedDate;
- (void)setSelectedDate:(NSDate *)newDate
{
@synchronized(_selectedDateComponents)
{
if (!newDate) return;
[_selectedDateComponents release];
int requiredComponents = NSDayDateComponent | NSMonthDateComponent | NSYearDateComponents;
_selectedDateComponents = [[_calendar components: requiredComponents fromDate:newDate] retain];
}
}
- (NSDate *)selectedDate
{
@synchronized(_selectedDateComponents)
{
if (!_selectedDateComponents) return nil;
return [_calendar dateFromComponents:_selectedDateComponents];
}
}
The class doesn't keep a reference to the object that is sent to the setter. None of the retain
, copy
or assign
seem appropriate. I like having this functionality encapsulated as a property but maybe a property is not appropriate.
What's your view?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您编写自己的设置器,那么使用什么并不重要。它仅作为对您自己/其他开发人员如何工作的提示。
属性类型仅真正影响
@synthesize
创建的方法。因此,如果您提供自己的方法,则您自己指定保留策略,并且声明中的属性策略通常会被忽略。在这种情况下,我会使用副本。因为,虽然您不使用直接副本,但您正在存储来自传入对象的值,并以非侵入性的方式将它们存储到该对象。因此,您将信息复制出来,只是转换成不同的格式。但就编译器而言,这根本不重要。当您编写自己的 setter 时,这纯粹是为了展示。
If you are writing your own setters, it doesn't matter what you use. It only serves as a hint to how it works to yourself/other developers.
The property type only really affects the methods created by
@synthesize
. So if you provide your own methods, you dictate the retain strategy yourself, and the property strategy form the declaration is mostly ignored.In this case I would use copy. Because, while you are not using a direct copy, you are storing value from that come from the passed in object and storing them in a non obtrusive way to that object. So you are copying the info out, just into a different format. But as far as the compiler cares, it doesn't really matter at all. It's purely for show when you write your own setter.