1

我在我的一个班级中有以下财产

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

我有以下方法来为这个属性分配内存。

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

    return children;
}

当我在 xcode 中运行分析器时,它显示我在上述方法中存在内存泄漏。我对在这种情况下释放内存感到困惑。如果我按如下方式将它与 autorelase 一起使用可以吗?

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

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

4

2 回答 2

1

为什么不让编译器为您完成工作?您可以执行以下操作:

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

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

至少对我来说,这要简​​单得多。

于 2012-05-29T08:40:09.020 回答
1

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

- (void)dealloc {
   [children release];
   ...
   [super dealloc];
}
于 2012-05-29T04:06:31.103 回答