【问题标题】:Memory leak coming from this code, how do i get rid of it?来自此代码的内存泄漏,我该如何摆脱它?
【发布时间】:2011-03-20 21:26:18
【问题描述】:

这是我的代码,应用程序在更改为它所在的视图时运行。当您多次更改此视图时(所以不是第一次运行它),它会导致 colourButtonsArray 发生内存泄漏,但我不确定如何摆脱它:

-(void)setColours {

        colourButtonsArray = [[NSMutableArray alloc] init];
        [colourButtonsArray addObject:@""];


    int buttonsI = 1;

    while (buttonsI < 7)
    {
        //Make a button
        UIButton *colourButton = [UIButton buttonWithType:UIButtonTypeCustom];
        colourButton.frame = CGRectMake((53*(buttonsI-1))+3, 5, 49, 49);
        colourButton.tag = buttonsI;
        [colourButton addTarget:self action:@selector(colourButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
    [colourView addSubview:colourButton];


        [colourButtonsArray addObject:colourButton];


[colourButton release];
    buttonsI++;
}

}

【问题讨论】:

  • 旁注:你不应该发布colourButton。您可以使用for 代替while

标签: iphone objective-c memory-leaks nsmutablearray


【解决方案1】:

你在哪里发布colourButtonsArray

如果您多次调用setColours,您将为colorButtonsArray 创建一个新数组并每次都泄漏旧数组(假设您只在您的dealloc 方法中释放colourButtonsArray,或者如果您不完全释放它)。

【讨论】:

  • 如果我把 [colorButtonsArray release];在 dealloc 中,然后当我第二次加载视图时,它崩溃了。
  • ...泄漏不会立即导致崩溃。你确定你没有在这里混淆术语吗?泄漏是当您不释放对象时,它仍然卡在内存中占用空间。如果您反复泄漏内存,您最终会导致崩溃(通过内存不足错误),但不会像这样的单个数组。听起来这里正在发生其他事情。
【解决方案2】:

正确使用访问器,并在必要时锁定。这可能会有所帮助:

-(void)setColours {
/* lock if necessary */
    self.colourButtonsArray = [NSMutableArray array];
    [self.colourButtonsArray addObject:@""];

    int buttonsI = 1;

    while (buttonsI < 7)
    {
    /* Make a button */
        UIButton *colourButton = [UIButton buttonWithType:UIButtonTypeCustom];
        colourButton.frame = CGRectMake((53*(buttonsI-1))+3, 5, 49, 49);
        colourButton.tag = buttonsI;
        [colourButton addTarget:self action:@selector(colourButtonPressed:) forControlEvents:UIControlEventTouchUpInside];
        [self.colourView addSubview:colourButton];

        [self.colourButtonsArray addObject:colourButton];

        // no release here: [colourButton release];
        buttonsI++;
    }

/* unlock if necessary */
}

【讨论】:

  • 你能解释一下'lock'是什么意思吗?我不明白。
猜你喜欢
  • 1970-01-01
  • 2020-09-18
  • 1970-01-01
  • 1970-01-01
  • 2020-09-22
  • 1970-01-01
  • 2022-07-30
  • 2011-02-18
  • 1970-01-01
相关资源
最近更新 更多