Search code examples
objective-cmemory-managementcopyretain

What are the semantics of using retain vs. copy for a property of type NSMutableSet;


I have been using the most excellent Accessorizer to auto-magically generate setters/getters for my Obj-C code in Xcode. Recently a change was made in Accessorizer:

old version of Accessorizer:
@property (nonatomic, retain) NSMutableSet *setA;
@property (nonatomic, retain) NSMutableSet *setB;

new version of Accessorizer:
@property (nonatomic, copy) NSMutableSet *setA;
@property (nonatomic, copy) NSMutableSet *setB;

Sadly, the new version crashes my code. In my code I do the following:

self.setA = [[[NSMutableSet alloc] init] autorelease];
self.setB = [[[NSMutableSet alloc] init] autorelease];

// ...

[self.setA minusSet:self.setB];  

The above line of code works fine using the old way (retain) but crashes using the new way (copy). Clearly something is wrong here. I rely on Accessorizer extensively. Could someone please clarify the implications of using copy/retain in the context of NSMutableSet?

Thanks,
Doug


Solution

  • If you're property type is a mutable set, you most likely want a retain. If it's a non-mutable set (aka NSSet), Apple's guidelines say to use copy rather than retain.

    The distinction is that there's an expectation that a mutable set is going to change. A non mutable set is expected to remain unchanged, but if it's declared as retain, someone could set it to a mutable set and then change the contents unexpectedly.