2012-05-29 17 views
1

我已经在我的课如何处理内存为只读属性

@property (nonatomic, retain, readonly) NSMutableArray *children; 

之一下列财产,我有以下的方法来分配内存这个属性。

- (NSMutableArray *)children { 
    if (!children) { 
     children = [[NSMutableArray alloc] initWithCapacity:1]; 
    } 

    return children; 
} 

当我在xcode中运行profiler时,它显示我在上面的方法中有内存泄漏。在这种情况下,我对释放记忆感到困惑。 如果我按照以下方式使用autorelase,可以吗?

children = [[[NSMutableArray alloc] initWithCapacity:1] autorelease]; 

有人可以帮我解决这个问题。

+0

如果您在类的''init'“或”'viewDidLoad'“方法(后者,如果它是视图控制器)中创建”children“,内存泄漏警告会消失吗? –

+0

你在用ARC编译吗? (我假设不是,但只是为了......) – Sean

+0

@Sean Im不使用ARC。 – nath

回答

1

你在dealloc中释放孩子吗?如果没有,那是你的问题!

- (void)dealloc { 
    [children release]; 
    ... 
    [super dealloc]; 
} 
+0

我已经发布了它在dealloc – nath

+0

好的,那么你的代码是完全没问题的。 Autorelease不是解决方案,它会让事情变得更糟。你的漏洞在代码 – iTukker

1

你为什么不让编译器为你做这个工作?您可以执行以下操作:

- (id) init { 
if(self=[super init]) { 
    children = [[NSMutableArray alloc] init] 
} 

使用dealloc iTukker向您显示并使属性合成。

至少对我而言,这是非常直接的。

+0

的其他地方我希望剖析器给我提供了错误的信息。因为看起来错误应该是在别的地方。谢谢你的帮助 – nath