【问题标题】:releasing all cells in tableview ios iphone释放tableview ios iphone中的所有单元格
【发布时间】:2011-07-20 17:09:14
【问题描述】:

我在 xcode 中通过分析发现了内存泄漏问题。这个问题很简单,但我不明白如何解决它:

考虑一个带有 2 个按钮和一个 tableview 的 uiviewcontroller。 button1=从服务器加载 JSON 数据并将单元格添加到 tableview 然后 [tableview reloadData]

button2=从另一个服务器加载 JSON 数据并将单元格添加到 tableview 然后重新加载。

好的,问题出在:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
....
.....
NSURL *url = [NSURL URLWithString:stringpath];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *img;
if(!data) img=[UIImage imageNamed:@"small.jpg"];
else img= [[UIImage alloc] initWithData:data];
cell.imageView.image = img;

好的,如果我每次切换时都用 2 个按钮开始切换,我会从 UIImage 泄漏,所以我认为我需要在重新加载之前“清除”(释放)所有单元格数据?

谢谢

【问题讨论】:

    标签: iphone ios memory-leaks tableview


    【解决方案1】:

    您不必为 UIImage 分配内存。您可以按如下方式执行上述实现:

    NSData *data = [NSData dataWithContentsOfURL:url];
    cell.imageView.image = [UIImage imageWithData: data];

    试试这个。

    【讨论】:

    • Thx Stone.. 我来自 c/c++,对我来说更容易考虑堆栈和堆。如果你在堆栈中分配,当你切换上下文和堆时,堆栈将被清除,你需要删除每个新的。目前ios中的内存管理仍然有点混乱。我从苹果那里读到了内存管理,但“如果你分配了你就释放”的规则并不总是正确的。也许有一天我会停止犯这样的错误。再次感谢。
    • 经过一些练习和阅读后,您肯定会对这个概念感到满意。 :)
    【解决方案2】:

    cell.imageView.image 中设置img 对象后,您应该释放它。我更喜欢autorelease 在同一行,因为这样我更容易跟踪。

    UIImage *img;
    if(!data) img=[UIImage imageNamed:@"small.jpg"];
    else img= [[[UIImage alloc] initWithData:data] autorelease];
    cell.imageView.image = img;
    

    正如另一个答案中提到的,您可以通过不使用initWithData 调用,而是使用imageWithData 来避免痛苦。

    细胞会自己照顾自己。

    【讨论】:

      【解决方案3】:

      我会替换这一行:

      else img= [[UIImage alloc] initWithData:data];
      

      与:

      else img= [UIImage imageWithData:data];
      

      【讨论】:

        【解决方案4】:

        问题是没有释放img,请在下面使用

        if (!data) 
        {
            img = [UIImage imageNamed:@"small.jpg"];
            cell.imageView.image = img;
        }
        else 
        {
            img = [[UIImage alloc] initWithData:data];
            cell.imageView.image = img;
            [img release];
        }
        

        【讨论】:

          猜你喜欢
          • 2010-11-18
          • 1970-01-01
          • 2023-03-08
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-10-11
          • 2014-12-30
          • 1970-01-01
          相关资源
          最近更新 更多