【问题标题】:iPhone Memory ManagementiPhone 内存管理
【发布时间】:2011-04-10 04:17:30
【问题描述】:

你好 Stackoverflow 的家人!

我有一个关于 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];
}

所以我理解对了吗?还是这里即使retain count达到> 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...

谢谢。

【问题讨论】:

    标签: iphone objective-c memory-management


    【解决方案1】:

    retainCount 不是可靠的调试工具:

    • 其他对象可能仍持有对obj 的引用
    • 有些对象无法销毁(例如string constants
    • 如果以 1 的保留计数释放对象,则会释放对象

    你应该注意什么:

    • 用适当数量的release/autorelease 平衡引用
    • 使用Analyzer
    • 使用Leaks

    【讨论】:

      【解决方案2】:

      这是不正确的,您应该很少使用retainCount。此时它不必为 0,因为其他对象可以引用您正在释放的对象。在 dealloc 中重要的是释放您拥有所有权的对象。这将是使用 alloc 或 new 等创建的对象。

      【讨论】:

        【解决方案3】:

        覆盖 dealloc 的正常过程是释放此实例先前保留(或分配)的所有对象。

        因此,如果您在对象的其他地方调用了 alloc 或 retain 方法,您的 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];
        }
        

        请注意,在您的特定发布之后发布计数是否没有降至零并不重要,这只是意味着其他一些代码也保留了对象内存(并且其他代码将负责释放它)。

        希望这会有所帮助。

        【讨论】:

          猜你喜欢
          • 2011-10-10
          • 2010-10-28
          相关资源
          最近更新 更多