与 Iphone 自动释放使用相关的问题
有人可以帮助我了解在以下场景中如何完成和处理分配和内存管理。我给出了一个 Psuedo 代码示例,困扰我的问题如下:
interface first
{ NSDecimalNumber *number1;
}
implementation
.....
-(void) dealloc {
[number1 release];
[super dealloc];
}
=================================
interface second
{ NSDecimalNumber *number2;
}
implementation second
.....
- (First*) check
{
First *firstObject = [[[First alloc] init] autorelease];
firstObject.number1 = [[NSDecimalNumber alloc] initWithInteger:0];
**// do i need to autorelease number1 as well?**
return firstObject;
}
Could someone help me please understand how allocation and memory management is done and handled in following scenario. i am giving a Psuedo code example and question thats troubling me is inline below:
interface first
{ NSDecimalNumber *number1;
}
implementation
.....
-(void) dealloc {
[number1 release];
[super dealloc];
}
=================================
interface second
{ NSDecimalNumber *number2;
}
implementation second
.....
- (First*) check
{
First *firstObject = [[[First alloc] init] autorelease];
firstObject.number1 = [[NSDecimalNumber alloc] initWithInteger:0];
**// do i need to autorelease number1 as well?**
return firstObject;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的代码是正确的。如果您自动释放该对象,其引用计数将达到零并且将被释放,然后如果您稍后尝试使用存储在 number1 中的值,您的应用程序将崩溃。
我要添加的唯一增强功能是释放任何现有的价值。即,
如果不这样做,则每次调用
check
时分配给number1
的前一个对象都会泄漏。Your code is correct as is. If you autoreleased the object, its reference count would reach zero and it would be dealloced, and then if you later tried to use the value stored in number1 your app would crash.
The only enhancement I'd add is releasing any existing value. i.e.
If you don't do this, the previous object assigned to
number1
will leak each timecheck
is called.当您分配 NSDecimalNumber 时,您需要释放它。 (正如您在 dealloc 中所做的那样。)
虽然很难根据示例代码提供有意义的示例(因为实际上并未使用“number1”),但一般规则是您对您所使用的任何对象负责。
分配
、复制
或新建
。如果该对象仅在函数范围内需要,您当然可以自动释放它。http://interfacelab.com/objective 有一篇很好的博客文章我建议阅读 -c-memory-management-for-lazy-people/ ,因为它提供了很好的示例(包括一些边缘情况)并且易于理解。
As you're allocing the NSDecimalNumber, you need to release it. (As you're doing so in the dealloc.)
Whilst it's hard to provide a meaningful example based on your sample code (as "number1" isn't actually used), the general rule is that you're responsible for any object you
alloc
,copy
ornew
. If the object was only required in the scope of a function, you could of course autorelease it.There's a good blog article over at http://interfacelab.com/objective-c-memory-management-for-lazy-people/ that I'd recommend reading as it provides good examples (including some edge cases) and is easy to follow.