简体   繁体   中英

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)? Also when would I used assign instead of retain?

Use nonatomic when you care more about performance than thread safety. Atomic properties are thread safe but slower. The default behaviour is atomic .

Use copy when you want a copy to be made whenever a new value is set to the property. 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 .

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. strong and retain are the same, and this is the default behaviour with ARC enabled. Just turn ARC on and ignore these ones, except for backwards compatible code.

Sometimes, for example delegate properties, using retain or strong would create a memory leak. In these situtaions you need to use weak or assign . In general, you should use weak , as assign can have rare edge case bugs.

Normally you @synthesize a property in your class implementation which creates a set function. 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];
}

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.

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