返回前释放局部变量?
在 Objective-C 中,我知道您需要释放您初始化/保留/复制的任何内容。我需要在 return
语句之前执行此操作吗?我想了解显式调用 release
而不是使用 autorelease
。
-(void) someMethod
{
AnotherClass* ac = [[AnotherClass alloc] init];
if([ac somethingHappens]){
// Do I need to release ac here?
return;
}
[ac doSomethingElse];
[ac release];
}
谢谢!
In objective-c, I understand that you need to release anything you init/retain/copy. Do I need to do that before a return
statement? I'm wanting to understand calling release
explicitly and not use autorelease
.
-(void) someMethod
{
AnotherClass* ac = [[AnotherClass alloc] init];
if([ac somethingHappens]){
// Do I need to release ac here?
return;
}
[ac doSomethingElse];
[ac release];
}
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
是的,您需要释放变量,但是您退出该方法。
这非常简单:当您初始化某些内容时,保留计数就会增加。当你释放它时,它会减少。当它达到零时,它会自动释放(释放)。
在上面的代码中,您初始化了变量,但如果它遵循返回路径,则变量保留计数永远不会为零,因此永远不会被释放。
Yes, you need to release your variables, however you exit from the method.
It's pretty straight-forward: when you init something the retain count is incremented. When you release it's decremented. When it reaches zero it's automatically deallocated (freed).
In your code above, you init the variable but if it follows the return route then the variables retain count never gets to zero and, therefore, is never deallocated.
假设有一个像下面这样分配的局部变量
现在将此变量传递给对象定义的方法,例如 UISearchBar 对象的 setPlaceholder
如何以正确的方式释放分配的字符串 'placeHolder' ?
如果你想自动释放它:
你的代码将会失败并出现 bad_exc_access
如果你想在传递到其他地方后释放变量,比如
运行时异常也会抛出。
那么出了什么问题呢?
问题是保留计数。 UISearchBar 对象尚未分配,因此如果您释放或自动释放该对象引用的此类变量,则保留计数仍然相同
那么,如何处理?
尝试类似以下的操作
我们做了什么?现在让我们看一下保留计数。
因此,我们在将其分配(被引用)给某个对象之前增加了保留计数,然后 - 之后 - 我们在本地释放该变量。
就这样。
Suppose to have a local variable assigned like the following
Now pass this variable to a object defined method, such as setPlaceholder of UISearchBar object
How to release in the right way the assigned string 'placeHolder' ?
If you suppose to autoreleas it:
your code will fail with a bad_exc_access
If you think to release the variable after passed to somewhere else like
a runtime exception will throw too.
So what's wrong?
The problem is the retain count. The UISearchBar object is allocated yet, so if you release or auto-release such a variable, referred by that object, the retain count is still the same
So, how to handle this?
Try something like the following
What we did than ? Let's have a look at the retain count now
So, we incremented the retain count before assign it (get referenced by) to some object, and - after that - we release locally that variable.
That's all.