objective-c - Objective-C 中的 C 数组维护指向已释放对象的指针

标签 objective-c arrays

从代码中:

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/

相关文章:

iOS 导航问题 : after pushing a ViewController, 导致导航栏显示上一个 ViewController 的导航项

ios - 指向原始类型的 Objective C 指针

iphone - NSDictionary 的描述性变量名称

arrays - 你能有 mongo $push prepend 而不是 append 吗?

java - 带大括号的赋值的数组语法错误

iphone - 专业人员如何检索 iPhone 应用程序中的数据? (数据库)

objective-c - iPhone 硬件和用户计时器随着时间的推移变得不同步

arrays - 创建要添加到数组的pscustomobject的正确方法

python - python中3d数组的最大值

Python - 数组中的字符串和数字,想要对行中的所有数值求和,并将值附加到行末尾