[英]Objective-C Mutable property, copy retain, etc?
When I declare a property for an interface that is Mutable should I always make it (nonatomic, copy)?当我为 Mutable 的接口声明一个属性时,我应该总是使它(非原子,复制)吗? Also when would I used assign instead of retain?
另外我什么时候会使用assign而不是retain?
Use nonatomic
when you care more about performance than thread safety.当您更关心性能而不是线程安全时,请使用
nonatomic
。 Atomic properties are thread safe but slower.原子属性是线程安全的,但速度较慢。 The default behaviour is
atomic
.默认行为是
atomic
。
Use copy
when you want a copy to be made whenever a new value is set to the property.如果您希望在为属性设置新值时进行复制,请使用
copy
。 Note that in many cases, copy
will not actually make a copy of the object, so this usually has no performance impact but can solve bugs if somebody gives you a mutable copy (eg, you have an NSString
property and somebody assigns an NSMutableString
.请注意,在许多情况下,
copy
不会实际制作对象的副本,因此这通常不会影响性能,但是如果有人给您一个可变副本(例如,您有一个NSString
属性并且有人分配了一个NSMutableString
,则可以解决错误。
Do not ever use retain
or strong
as these are only needed when ARC is turned off, and you should always have ARC turned on.永远不要使用
retain
或strong
因为它们只在 ARC 关闭时才需要,并且您应该始终打开 ARC。 strong
and retain
are the same, and this is the default behaviour with ARC enabled. strong
和retain
是相同的,这是启用 ARC 的默认行为。 Just turn ARC on and ignore these ones, except for backwards compatible code.只需打开 ARC 并忽略这些,除了向后兼容的代码。
Sometimes, for example delegate properties, using retain
or strong
would create a memory leak.有时,例如委托属性,使用
retain
或strong
会造成内存泄漏。 In these situtaions you need to use weak
or assign
.在这些情况下,您需要使用
weak
或assign
。 In general, you should use weak
, as assign
can have rare edge case bugs.通常,您应该使用
weak
,因为assign
可能会出现罕见的边缘情况错误。
Normally you @synthesize
a property in your class implementation which creates a set function.通常,您在类实现中
@synthesize
一个属性,它创建一个 set 函数。 You can write your own property set function, and do a mutable copy there.您可以编写自己的属性集函数,并在那里进行可变副本。 Problem solved...
问题解决了...
- (void)setPropertyName:(propertyType *)newProperty {
if (propertyName) [propertyName release];
propertyName = [newProperty mutableCopy];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.