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

后端 未结 6 1152
逝去的感伤
逝去的感伤 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 12:01

    I ran into the same problem some time ago and found a document on the Apple Developer Connection recommending to provide your own implementation of the setter. Code sample form the linked document:

    @interface MyClass : NSObject {
        NSMutableArray *myArray;
    }
    @property (nonatomic, copy) NSMutableArray *myArray;
    @end
    
    @implementation MyClass
    
    @synthesize myArray;
    
    - (void)setMyArray:(NSMutableArray *)newArray {
        if (myArray != newArray) {
            [myArray release];
            myArray = [newArray mutableCopy];
        }
    }
    

提交回复
热议问题