【问题标题】:Can you alloc an object whose parent class uses the autorelease pool?你能分配一个其父类使用自动释放池的对象吗?
【发布时间】:2011-01-03 14:22:53
【问题描述】:

我有一个子类,我使用 alloc 和 init 来实例化。在init方法中我去

self = [self initWithRect:spriteManager.imageRect spriteManager:spriteManager.manager];

所以父构造函数正在使用自动释放池。那么这里会发生什么?如果我尝试释放该对象,则会出现错误。我是否应该将我的 init 方法更改为方便的构造函数以符合分配、复制、新所有权策略?

【问题讨论】:

    标签: objective-c memory-management


    【解决方案1】:

    超类的初始化器 -initWithRect:spriteManager: 将对象放入自动释放池中。命名约定是任何 -init... 方法都会设置一个您负责释放的对象。

    Xcode 为 init 和 dealloc 方法提供了有用的代码完成模板。只需按 control-comma 并开始输入“init”或“dealloc”。 (您也可以输入 init 并按 control-comma。)init 模板是

    - (id) init
    {
        self = [super init];
        if (self != nil)
        {
            // Your initializations
        }
        return self;
    }
    

    你将self = [super init] 替换为你上面写的那行。

    dealloc 模板是

    - (void) dealloc
    {
        // Your deallocations
        [super dealloc];
    }
    

    [super dealloc] 调用超类的 -dealloc,它会负责释放它在 -initWithRect:spriteManager: 调用中设置的任何内容(以及它从其超类继承的任何内容)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多