2011-09-19 75 views
0

在我的一个函数中,我有一个while循环,可能需要临时创建一个对象。我的代码如下所示:我什么时候可以释放一个对象?

while(c < end){ 
    if(specialCase){ 
     Object *myObject = [Object alloc]; 
     //do stuff with myObject 
     //I tried [myObject dealloc] here, but it crashed when this method was called. 
    } 
    c++; 
} 

该代码正常工作,但我担心内存泄漏。我想知道是否和如何我应该dealloc myObject。

回答

5

你从不直接调用Dealloc。

你打电话发布,当保留计数达到0时,dealloc将在对象上调用。

+0

谢谢!我试图在dealloc之前的某个时刻调用release,并得到错误的访问错误。我想现在我知道为什么。 – WolfLink

1

你不应该直接调用dealloc方法,它们要么allocedretain将调用dealloc含蓄调用对象的release,如果保留计数对象满足与条件由的iOS系统放(通常如果保留计数ZERO为对象)。

阅读dealloc方法的苹果文档中NSObject类,也经过Memory Management Programming Guide客观-C

0

试试这个

while(c < end){ 
if(specialCase){ 
Object *myObject = [[Object alloc] autorelease]; 
    //do stuff with myObject 
    //I tried [myObject dealloc] here, but it crashed when this method was called. 
} 
c++; 

}

0

你也许可以尝试使用智能指针。 这应该照顾垃圾收集和任何异常处理。另外,Boost库可以移植到ios上。

相关问题