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

后端 未结 6 1151
逝去的感伤
逝去的感伤 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:57

    It's not common to pass around NSMutableArrays in Cocoa. Standard Cocoa practice would be to implement the key-value coding compliant methods for an indexed to-many property. This has two benefits:

    1. Key-value observing works as expected (there are several cases where observing an NSMutableArray leads to not-what-you-want behavior)
    2. The implementation of your data structure is hidden because you expose mutating methods (e.g. -[MyObject insertObjectInMyProperty:(id)newObject atIndex:(NSUInteger)i] , not the data structure itself.

提交回复
热议问题