我以为我已经开始掌握objective-c中内存管理的诀窍了,但是我对将集合相加得到的保留计数感到有点困惑。setByAddingObjectsFromSet的应用编程接口说:
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?我必须释放它两次吗?!我误解了什么?
非常感谢。
发布于 2011-05-13 03:21:14
你根本不需要发布它。实际上,你不能释放它。你不拥有它。这些保留物来自Cocoa,这是Cocoa的责任来照顾它-它们不是你关心的。(这是查看retainCount不可取的众多原因之一。)
https://stackoverflow.com/questions/5983193
复制相似问题