简体   繁体   English

为什么用“ self”设置值会导致内存泄漏?

[英]Why setting value with “self” cause memory leak?

I need to understand why in this code i get a memory leak if i assign value to ws_data variable using self.ws_data and not if i use only ws_data. 我需要了解为什么在此代码中,如果我使用self.ws_data将ws_data变量赋值,而我仅使用ws_data而不赋值,则会发生内存泄漏。

self.ws_data is a @property (copy)NSString *, released on dealloc. self.ws_data是@property(副本)NSString *,在dealloc上发布。

dispatch_queue_t ws_queue = dispatch_queue_create("ws check win", NULL);
dispatch_async(ws_queue, ^{
    self.ws_data = [[NSString alloc]initWithContentsOfURL:url]; 
});
dispatch_release(ws_queue);

Thank you! 谢谢!

self.variableName accesses the variable through its accessors. self.variableName通过其访问器访问变量。 Because your ws_data NSString is set to copy in its property declaration, the string is retained when you set it through that declaration. 由于您的ws_data NSString设置为在其属性声明中进行复制 ,因此在通过该声明进行设置时会保留该字符串。

Not using self. 不使用自我。 references the ivar without going through those accessors. 无需通过那些访问器即可引用ivar。 It also means the variable isn't copied, so it will vanish when references to it disappear (like at the end of your method). 这也意味着该变量不会被复制,因此当对它的引用消失时(如方法末尾)它将消失。

Odds are you want the copy. 您需要副本的可能性很大。 You just need to release it when you're done, as you do in your dealloc. 您只需要在完成操作后释放它,就像在dealloc中一样。

Are you retaining it somewhere else, making this access a second retention? 您是否将其保留在其他位置,从而使此访问权限成为第二保留?

If I understand things correctly (and I quite possibly don't as I've not be doing iOS development for very long at all) in this instance, as you're using the copy attribute on the property, what you're doing when you use self.ws_data is effectively calling the copy method on an already alloced NSString, which is creating a separate instance of the NSString with a retain count of one. 如果在这种情况下我理解正确(并且可能很长一段时间都没有进行iOS开发),因为您在属性上使用copy属性,那么您在做什么时您使用self.ws_data可以有效地在已分配的NSString上调用copy方法,该方法将创建一个保留计数为1的NSString的单独实例。

However, the original NSString (that's being alloced in your above sample) isn't being released at any point, hence the leak. 但是,原始的NSString(在上面的示例中分配的)在任何时候都不会释放,因此会泄漏。

You could use... 你可以用...

self.ws_data = [[[NSString alloc]initWithContentsOfURL:url] autorelease]; 

...instead, I'd have thought. ...相反,我原本以为。

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

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