简体   繁体   English

这个objective-c代码会导致内存泄漏吗?

[英]Does this objective-c code cause memory leak?

Compare the following 2 snippets: 比较以下2个片段:

sample 1: 样本1:

[[UIApplication shareApplication] openURL: [NSURL URLWithString:@"http://stackoverflow.com"]]

and sample 2: 和样本2:

NSURL *url = [[NSUrl URLWithString:@"http://stackoverflow.com"];
[[UIApplication shareApplication] openURL: url];
[url release];

Does sample 1 cause memory leak? 样品1会导致内存泄漏吗? is [url release] in sample 2 redundant? 样本2中的[url release]是多余的?

If memory leak does happen, how bad is it? 如果确实发生了内存泄漏,那有多糟糕?

Sample 1 does not cause a memory leak and is the general way to do it. 示例1不会导致内存泄漏,并且是执行此操作的一般方法。 The NSURL object is autoreleased, and thus you're not supposed to release it yourself (as you do in sample 2). NSURL对象是自动释放的,因此您不应该自己释放它(正如您在示例2中所做的那样)。

Sample 1 is perfectly fine, as was already described above. 如上所述,样品1非常精细。 However, sample 2 should actually result in a crash. 但是,样本2实际上应该导致崩溃。 -URLWithString: is autoreleased, so its retain count is effectively already going to be zero when the next autorelease pool is drained. -URLWithString:是自动释放的,因此当下一个自动释放池耗尽时,其保留计数实际上已经为零。 Releasing it explicitly like you're doing will bring its retain count to 0 immediately, resulting in deallocation. 像你正在做的那样明确地释放它会立即将其保留计数设为0,从而导致释放。 Then, when the autorelease pool is drained, it'll try to release that string again, resulting in a crash. 然后,当自动释放池耗尽时,它将再次尝试释放该字符串,从而导致崩溃。

It's always best to use the Build and Analyze command in Xcode. 最好在Xcode中使用Build and Analyze命令。 It can pick up and warn you about almost all memory leak issues, although it's not perfect. 它可以接收并警告你几乎所有的内存泄漏问题,虽然它并不完美。 Still, it's a good practice. 不过,这是一个很好的做法。

@BoltClock, I think you are not entirely correct in saying that the object is autoreleased in sample 1. @BoltClock,我认为在样本1中对象是自动释放的并不完全正确。

In sample 2, a variable named url is assigned the object returned from the [NSUrl URLWithString:] method, thus incrementing its retain count by 1. To balance that, we need to release it. 在示例2中,名为url的变量被赋予从[NSUrl URLWithString:]方法返回的对象,从而将其保留计数增加1.为了平衡它,我们需要release它。 While in sample 1, the reference to the object is directly passed to the receiver and we have nothing to worry about its retain count, hence no release. 在样本1中,对对象的引用直接传递给接收者,我们没有什么可担心它的保留计数,因此没有释放。

Note that we are not autoreleasing, since we have not retained anything in the first place. 请注意,我们不是自动释放,因为我们首先没有保留任何内容。 "There is no variable in the code that is being autoreleased!" “代码中没有自动释放的变量!”

Please correct me if I am conceptually wrong somewhere. 如果我在某个地方概念上错了,请纠正我。 And just to complete this, there is no leak in either of the samples and both are correct ways of doing this. 只是为了完成这一点,任何一个样本都没有泄漏,两者都是正确的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM