如何管理自动释放对象的内存
我致力于扑克牌类的实现,并且创建了以下方法:
+ (id)cardWithCard:(Card *)newCard
{
Card *card = [[[Card alloc] initWithCard:newCard] autorelease];
return card;
}
我在这里使用 autorelease 方法,否则 Product->Analyze 会警告我潜在的泄漏。一切正常,直到变量 myCard(之前分配的)被分配了新值,如下所示:myCard = [Card cardWithCard:newCard]
作为参数发送到不同的方法。结果它被释放了,我的应用程序崩溃了。 我应该如何解决这个问题?尽管有分析警告,仍要放弃自动释放方法吗?
I work on implementation of playing card class and i've created the following method:
+ (id)cardWithCard:(Card *)newCard
{
Card *card = [[[Card alloc] initWithCard:newCard] autorelease];
return card;
}
i use autorelease method here cause otherwise Product->Analyze warns me about potential leak. Everything works fine until variable myCard (which was allocated earlier) to which a new value was assigned like this:myCard = [Card cardWithCard:newCard]
is sent to a different method as a parameter. It turns out to be deallocated there and my app crashes.
How should i resolve this issue? Get autorelease method away despite warnings of Analyze?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
每个方法或对象都应该负责保留它感兴趣的对象。
它更容易维护。 (例外情况是名称中包含
alloc
、new
或copy
的方法,它们将返回调用者负责的对象release
。)因此您需要保留
autorelease
,因为该方法在return
之后不存在,并且无法对其调用release .如果调用
cardWithCard
的对象希望该对象的活动时间超过该特定方法的时间,则应该保留
该对象。代码应该看起来像这样
这是在
myCard
声明如下的情况下所以在这种情况下,该属性将为您保留并在您将新对象放入时释放该对象此属性。 (如果您覆盖自动生成的访问器,则需要在这些方法中自行管理)
如果由于某种原因您不想使用属性......那么这是您的选择:-)
你将需要做这样的事情:
并且稍后你将需要做这样的事情
如果它不是在同一个方法中,分析器将遵守,如果它在同一个方法中,你可能不需要
retain< /代码>。
Each method or object should be responsible for retaining object that it is interested in.
It it easier to maintain. (Exception are for method that have
alloc
,new
orcopy
in there name, they will return an object that the caller is responsible torelease
.)So you need to keep the
autorelease
because that method don't exist after thereturn
and won't be able to call release on it.The Object that is calling
cardWithCard
shouldretain
the object if it want it to be alive more that the time of that particular method.The code should look something like this
This is in the case where
myCard
is declare like thisSo in this case the property will do the retain for you and will release that object when you will place a new one in this property. (If you overwrite the auto-generated accessor, you will need to manage that yourself in those method)
If for some reason you don't want to use a property... well it's your choice :-)
You will need to do something like this:
and you will need to something like this later on
If it's not in the same method the analyser will compline, and if it's in the same method you probably don't need the
retain
.