iPhone:这是不是泄漏 [英] iPhone: Is this a leak or not

查看:216
本文介绍了iPhone:这是不是泄漏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近有人在Stack Overflow上告诉我,下面的代码没有泄漏,该属性处理保留本身:

Recently someone on Stack Overflow told me that the code below does not leak, that the property handles retention itself:

self.locationManager = [[CLLocationManager alloc] init];

in dealloc:

in dealloc :

   self.locationManager = nil;

.h文件中的位置:

@property (nonatomic, retain) CLLocationManager *locationManager;

我认为这是一个明显的泄漏,并认为这应该可以解决泄漏:

I thought that was an obvious leak and believed this should fix the leak:

self.locationManager = [[[CLLocationManager alloc] init] autorelease];

然而他声称这不起作用,因为用他的话说:你不自动释放属性一个类。定义为保留的属性的自动生成的访问器将自动处理保留

However he claimed that would not work, because in his words : "you don't autorelease properties of a class. The autogenerated accessor of a property defined to retain will handle retention automatically"

他让我想知道他是错了还是我根本不理解内存管理?

And he made me wonder if he is wrong or have I not understood memory management at all?

编辑1 :代码是

self.myName=[NSSting stringWithFormat:@"%@ is correct.", @"TechZen"];

任何不同于

 self.locationManager = [[[CLLocationManager alloc] init] autorelease];

内存管理方式?

家伙说第一个是正确的,拒绝第二个。为什么第二个会出错?据我所知,两者都将自动释放的实例分配给某些属性,但不知怎的,仍有一个固执的论点,即第二个错误。我看不到它,任何帮助都会如此受欢迎。

The guy says the first one is correct and refuses the second one. Why would the second one be SO WRONG? As far as I can see both assign autoreleased instances to some properties, but somehow there's still a stubborn argument that second one is wrong. I cannot see it, any help would be so welcome.

推荐答案

在这种情况下,计算保留和释放有帮助。这绝对是一个泄漏。您的 locationManager 对象将被保留2次:一次是 alloc / init 调用,一次是属性。将属性设置为 nil 只会释放 locationManager 一次。

Counting retains and releases helps in this case. It is most definitely a leak. Your locationManager object will be retained 2 times: once by the alloc/init calls, and once by the property. Setting the property to nil will only release the locationManager once.

对于编辑1中给出的示例,它们确实是相同的。这听起来像其他开发人员厌恶立即自动释放或不太明白 autorelease 是什么。

For the examples given in Edit 1, they are indeed the same. It sounds like the other developer has an aversion to immediately autoreleasing or doesn't quite understand what autorelease does.

这篇关于iPhone:这是不是泄漏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆