2010-09-09 86 views
1

你好Stackoverflow家庭成员!iPhone内存管理

我有关于iPhone内存管理的问题。

我所做的理解是以下方法

-(void) dealloc 
{ 
    // something else to release whatever 
    // such as Object Created using keyword 'alloc' 
    // but also Object destroy here its retain value reaches iff 0 
    // if I do put here NSLog(@"%d", [obj retainCount]); and when it reaches 
    // not equal to 0 means failure with memory leak. 
    [super dealloc]; 
} 

所以我是明白了吧?或者即使保留计数在这里达到0以上,它仍然很亮?

我之所以问这个问题,因为,

NSLog(@"%d", obj.retainCount); 

检查,以检查保留对象的数量和接收到的值3。于是,我就在这里释放的3倍,使这里retainCount等于0,但编译器给我提供了严重错误。

请问,我是新来的内存解除分配和保留,释放。我用

对象是 '的UIImageView' 对象,并创建另一个实例是,

UIImageView *imageView = //da da~ with UIImage 
UIImageView *instance; 
// at this point retain count was '1' 
instance = imageView; 
//[imageView retain]; 
// at this point retain count was '2' 
[self.view addSubView: imageView]; 
// at this point retain count was '3' 
[imageView release];// crashes 
// at this point retain count was '2' 

,但如果我这样做

// but if I add retain on the 'instance = imageView' 
// such as 
instance = imageView; // then 
[imageView retain]; 
// works but still count is 2... 

谢谢。

回答

1

覆盖dealloc的正常过程是释放之前由此实例保留(或分配)的任何对象。

所以,如果某处对象否则你有一个名为页头或保留方法您的dealloc会是什么样子:

-(void)someOtherMethod 
{ 
    UIImageView *imageView = //da da~ with UIImage 
    UIImageView *instance; 
    instance = imageView; 
    [instance retain]; 
} 

-(void) dealloc 
{ 
    //release any retained objects here 
    [instance release]   
    [super dealloc]; 
} 

注意,如果推出后,计数未下降到零也无所谓你的特定版本,这只是意味着其他一些代码也保留了对象内存(而另一部分代码将负责释放它)。

希望这会有所帮助。

5

retainCount不是一个可靠的调试工具:

  • 其他对象可能仍然持有引用obj
  • 还有,你不能破坏物体(如string constants
  • 对象被释放,如果发布时保留数为1

你应该照顾的是:

0

这是不正确的release/autorelease

  • 适量,你应该很少使用retainCount。它不一定是0,因为其他对象可能会引用正在释放的对象。在dealloc中重要的是释放你拥有所有权的对象。哪些是使用alloc或new创建的对象。