Debugger That
Debugger That

Reputation: 97

NSSet setByAddingObjectsFromSet retain count

I thought I was starting to the hang of memory management in objective-c but I'm a little confused by the retain count I'm getting from adding sets together. The api for setByAddingObjectsFromSet says:

Returns a new set formed by adding the objects in a given set to the receiving set.

- (NSSet *)setByAddingObjectsFromSet:(NSSet *)other

So I'm a bit puzzled by this:

NSSet* tom = [[NSMutableSet alloc] initWithCapacity:1];
NSSet* dick = [[NSMutableSet alloc] initWithCapacity:1];
NSSet* harry = [tom setByAddingObjectsFromSet:dick];

printf("tom   retainCount: %d \n", [tom retainCount]);
printf("dick  retainCount: %d \n", [dick retainCount]);
printf("harry retainCount: %d \n", [harry retainCount]);

Which produces:

tom   retainCount: 1 
dick  retainCount: 1 
harry retainCount: 2 

If setByAddingObjectsFromSet returns a new set why is the retainCount 2? Do I have to release it twice?! What have I misunderstood?

Thanks alot.

Upvotes: 0

Views: 629

Answers (1)

Chuck
Chuck

Reputation: 237110

You don't have to release it at all. Actually, you must not release it. You don't own it. Those retains are from Cocoa, and it's Cocoa's responsibility to take care of it — they're not your concern. (This is one of the many reasons why looking at retainCount is inadvisable.)

Upvotes: 2

Related Questions