What's the best way to use Obj-C 2.0 Properties with mutable objects, such as NSMutableArray?

后端 未结 6 1156
逝去的感伤
逝去的感伤 2020-11-30 11:13

I have an Obj-C 2.0 class that has an NSMutableArray property. If I use the following code, then the synthesised setter will give me an immutable copy, not a mutable one:

6条回答
  •  难免孤独
    2020-11-30 11:56

    The right way to hold on to a NSMutableArray is with a retain property:

    @property (nonatomic, retain) NSMutableArray *myArray;
    

    You do not need to write your own setter or use copy. The copy property should be used with a NSArray that actually does need to be copied when the property is captured into another object. For example, if you assign a NSMutableArray object to a property that is of type NSArray with the copy property, then you do want to make a copy of the mutable array to "capture" it as an immutable property from that point forward.

    And Marc has the right approach, one would not normally make NSMutableArray a part of the public API of your objects. If you do have a public property, it can be a NSArray with the copy property.

提交回复
热议问题