【问题标题】:Leaks on componentsSeparatedByString and stringWithFormat, is there a better way to do this?componentsSeparatedByString 和 stringWithFormat 泄漏,有没有更好的方法来做到这一点?
【发布时间】:2010-09-10 18:13:17
【问题描述】:

Instruments 中的这段代码导致大量内存泄漏。

这里:

NSArray *tmpCoords = [loc.mapCoords componentsSeparatedByString:@","];

这里:

    coords.tileRow = [NSString stringWithFormat:@"%d",x];
    coords.tileCol = [NSString stringWithFormat:@"%d",y];

有没有更好的方法来做到这一点?我基本上是在解析一个字符串并将东西添加到一个数组中。我该如何清理?

更新:CoordinateArray 保留在 .h 中并在 dealloc 中释放。应该在前面提到。 完整代码:

-(void)loadCoordinates
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];  
    // get list of coordinates once
    coordinateArray = [[NSMutableArray alloc] init];

    MyAppDelegate *app = [[UIApplication sharedApplication] delegate];
    MyData *myData = app.data;

    NSArray *myArray = [myData locations];

    for ( NSUInteger i = 0; i < [myArray count]; i++ )
    {
        LocationModel *loc = [myArray objectAtIndex:i];
        NSArray *tmpCoords = [loc.mapCoords componentsSeparatedByString:@","];
        if ([tmpCoords count] < 2 ) continue;
        CoordinateModel *coords = [[CoordinateModel alloc] init];

        coords.row = [tmpCoords objectAtIndex:0];
        coords.col = [tmpCoords objectAtIndex:1];

        NSString *xString = [tmpCoords objectAtIndex:0];
        int x = [xString floatValue] / DEFAULT_TILE_SIZE;
        NSString *yString = [tmpCoords objectAtIndex:1];
        int y = [yString floatValue] / DEFAULT_TILE_SIZE;

        coords.tileRow = [NSString stringWithFormat:@"%d",x];
        coords.tileCol = [NSString stringWithFormat:@"%d",y];

        [coordinateArray addObject:coords];
        [coords release];

    }
    [pool release];   
}

【问题讨论】:

  • 只是出于好奇,LocationModel 和 CoordinateModel CoreData 是自动生成的类吗?
  • 不,LocationModel 和 CoordinateModel 是我创建的类,它们继承自 NSObject。它们不是 CoreData 对象。

标签: iphone objective-c memory memory-leaks


【解决方案1】:

您的坐标对象上的属性很可能被声明为retaincopy,而您忘记在坐标的dealloc 方法中release 它们。

泄漏工具显示泄漏对象的创建位置,而不是丢失的位置。

【讨论】:

  • 戴夫,很好的评论。但是,coordinateArray 在 .h 中保留并在 dealloc 中释放。 Instruments 确实可以追溯到这两个对象(componentsSeparatedByString、stringWithFormat)。我承认,我也没有看到任何明显的东西。约旦
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-08
  • 2011-03-10
  • 1970-01-01
相关资源
最近更新 更多