我们可以在 Objective-c 中释放一些变量不拥有但指向的内存吗?
我有一些这样的代码:
NSObject *var1 = [[NSObject alloc] init];
NSObject *var2 = var1;
[var2 release];
var1 = nil;
这是正确的还是内存泄漏? 据我所知,只有 var1 可以释放第一行中分配的内存,根据 对象所有权政策
I have some code like this:
NSObject *var1 = [[NSObject alloc] init];
NSObject *var2 = var1;
[var2 release];
var1 = nil;
Is this correct or is this a memory leak?
As far as I know only var1 can release the memory alloc-inited in the first line, as per the Object Ownership policy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您的代码将释放内存,因为只有一次分配和一次释放 - 指向对象的指针数量不是一个因素。
所有权是一个对象所有权政策 谈论的是,因为如果您遵循这些准则,它会更容易管理并最终防止与发布您不应该发布的内容相关的问题(或者不释放你应该释放的东西)。
Your code will release the memory, because there is a single alloc, and a single release - the amount of pointers to the object is not a factor.
Ownership is a concept that the Object Ownership policy talks about because if you follow the guidelines it makes it easier to manage and ultimately prevent problems relating to releasing things you shouldn't release (or not releasing things you should).
你的代码没问题,没有泄露。但看来你并没有真正理解指针。指针不能拥有另一个对象,它只是一个引用,告诉计算机正在访问哪个对象。在 Cocoa 的引用计数内存模型中,有多少个指针指向单个对象根本不重要。
在尝试学习 Objective-C 之前,你确实应该学习 C(尤其是指针)。
Your code is all right and doesn't leak. But it seems like you don’t really understand pointers. A pointer can not own another object, it is just a reference that tells the computer which object is being accessed. In the reference-counted memory model of Cocoa it doesn’t matter at all how many pointers point to a single object.
You really should learn C (especially about pointers) before you try to learn Objective-C.
您的示例不会导致内存泄漏,因为
var1
和var2
指向内存中的同一对象,因此alloc
调用具有匹配的 <代码>发布。但是,如果NSObject
在分配给var2
时被保留,则会出现内存泄漏,因为没有匹配的release
。当内存管理指南谈到所有权的概念时,并不意味着变量(例如
var1
)拥有一个对象;而是意味着变量(例如var1
)拥有一个对象。更多的是关于它的“范围”(例如类或方法)。在您的示例中,包含这些语句的方法将负责释放该对象。Your example will not result in a memory leak as
var1
andvar2
point to the same object in memory—thus thealloc
call has a matchingrelease
. If theNSObject
was retained as it was assigned tovar2
however, there would be a memory leak as there would be no matchingrelease
.When the memory management guide talks about the concept of ownership, it doesn't mean that a variable (e.g.
var1
) owns an object; it's more about what "scope" owns it (e.g. a class or method). In your example, the method containing those statements would be responsible for releasing the object.保存引用计数的是对象,而不是指向对象的指针。如果你有十几个指向一个对象的指针,你可以使用其中任何一个来释放该对象,因为它们都指向同一个对象。但是,如果您不玩这类游戏,那么遵循您的代码并确保不会出现内存管理问题会容易得多。
It's the object that keeps a reference count, not the pointer to the object. If you have a dozen pointers to an object, you could use any one of them to release the object because they're all pointing to the same object. However, it's a lot easier to follow your code and make sure that you don't have memory management problems if you don't play those sorts of games.