NSArray property: copy or retain?

后端 未结 4 1559
醉话见心
醉话见心 2021-02-04 02:04

According to this: NSString property: copy or retain?

For NSString/NSMutableString, copy is recommended.

How about NSArray/NSMutableArray?

4条回答
  •  醉话见心
    2021-02-04 02:34

    From the link you included, it pretty much comes down to this: NSString property: copy or retain?

    If you want to make sure the value of the object won't change during execution, you use the copy attribute, otherwise retain will be fine. Generally, retain will be ok for NSMutableArrays and NSArrays (as well as many other objects) as you are (usually) more interested in the object then in the value it contains. In case of an NSString you are always interested in the value, so you copy it to make sure it won't change.

    @jlehr:

    It depends if the developer is interested in the actual value or not. Whenever interested in the actual value, use copy (since you don't want the value to change during execution), otherwise retain is fine. From Apple's docs:

    It is common practice in Objective-C code to copy value objects—objects that represent attributes. C-type variables can usually be substituted for value objects, but value objects have the advantage of encapsulating convenient utilities for common manipulations. For example, NSString objects are used instead of character pointers because they encapsulate encoding and storage.

    Also from Apple's docs, on the topic of value objects:

    A value object is in essence an object-oriented wrapper for a simple data element such as a string, number, or date. The common value classes in Cocoa are NSString, NSDate, and NSNumber. Value objects are often attributes of other custom objects you create.

提交回复
热议问题