从代码中:
Thing *thingA = [[Thing alloc]init];
// thingA pointer reference 0x00998
Thing *things[] = {thingA};
[thingA release];
// release method of the Thing class correctly invoked
thingA = nil;
// thingA pointer reference now is 0x0
NSLog(@"%d", things[0]);
// odd, because things[0] still maintains the pointer reference 0x00998
为什么元素things[0]
维护指针引用0x00998
?
在 thingA
通过 release
进行 dealloc
的那一刻,然后设置为 nil
(对 的引用) thingA
现在是 0x0
))为什么 things[0]
仍然是对 0x0998
的引用?
我认为 things[0]
指针看起来会是 0x0
。
最佳答案
行thingA = nil;
仅影响thingA
引用。它不会影响任何其他引用或对象本身。
您可以使这个示例更简单一些
Thing *thingA = [[Thing alloc]init];
Thing *thingB = thingA;
[thingA release];
thingA = nil;
// thingA is nil, but thingB still has old reference
请注意,由于对象本身已被释放,因此您不应使用 thingB
引用:它指向的内存可能已用于其他用途。
关于objective-c - Objective-C 中的 C 数组维护指向已释放对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5124715/