初始化一个对象,然后将其存储到NSArray中.这会是泄漏吗? [英] Init an object, then store it into an NSArray. Is this going to be a leak?

查看:45
本文介绍了初始化一个对象,然后将其存储到NSArray中.这会是泄漏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我保留了一个初始化的对象,那么我拥有它,并将其存储在NSArray中,该对象保留了存储在其中的对象,我可以依靠NSArray来查看它是否已保留并且不增加计数,还是我需要遍历数组并减少保留计数以确保没有内存泄漏?

If an inited object comes to me retained, so I own it, and I store it in an NSArray, which retains that which gets stored in it, can I count on NSArray to see that it's already retained and not increase the count, or do I need to run through the array and decrement the retain count to insure no memory leak?

推荐答案

要确保放弃添加到NSArray中的对象的所有权,请在添加后立即向对象发送-release消息将其保存到NSArray.如果不这样做,则确实会发生内存泄漏.

To make sure that the ownership of the object which was added into the NSArray is relinquished, send the -release message to the object right after you add it to the NSArray. If you do not do this, then you will indeed have a memory leak.

会发生这种情况:

NSString *str = [[NSString alloc] initWithFormat:@"%@", @"Blah"]; //retain count is 1, you own this object
[array addObject:str]; //retain count gets bumped to 2
[str release]; //retain count is 1 - relinquishing ownership here.
//There is no leak because when the NSArray is
//deallocated, the object will be sent the release message.

但是,如果您向拥有的插入对象发送-release消息,则即使释放NSArray,该对象的保留计数也只会为1,并且该对象获得的内存将永远无法回收,从而导致泄漏.

But if you don't send the owned inserted object the -release message, then even when the NSArray is deallocated, the object will only have a retain count of 1 and the memory obtained by the object will never be reclaimed, thereby resulting in a leak.

这篇关于初始化一个对象,然后将其存储到NSArray中.这会是泄漏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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