我以为我开始掌握objective-c中的内存管理,但我对将集合加在一起得到的保留计数有点困惑。setByAddingObjectsFromSet 的 api 说:
Returns a new set formed by adding the objects in a given set to the receiving set.
- (NSSet *)setByAddingObjectsFromSet:(NSSet *)other
所以我对此有点困惑:
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]);
产生:
tom retainCount: 1
dick retainCount: 1
harry retainCount: 2
如果 setByAddingObjectsFromSet 返回一个新集合,为什么 retainCount 为 2?我必须释放它两次吗?我误解了什么?
非常感谢。