对象泄露......我该如何解决?

时间:2010-08-24 20:36:09

标签: iphone memory-leaks

当我做“构建和分析”时,xCode给出了以下警告:

在第70行分配的对象的潜在泄漏

  1. Method返回一个带有+1保留计数的Objective-C对象(拥有引用)

  2. 循环回到循环的头部

  3. 在此点之后不再引用第70行上分配的对象,并且保留计数为+1(对象泄露)

  4. 这是代码(第70行是以“NSString * newString”开头的代码):

    for(int j = 1; j < [smokeArray count]; j++) {
    
        NSString *newString = [[NSString alloc] initWithFormat:@"Data: "]; 
        int f = [[[smokeArray objectAtIndex:j] num] intValue];
    
        for (int i = 0; i<6; i++) {
            int d = [[[[smokeArray objectAtIndex:j] dat] objectAtIndex:i] intValue];
    
            if (i>0) {  newString = [newString stringByAppendingFormat:@"-%d",d];   }
            else {  newString = [newString stringByAppendingFormat:@"%d",d];  }
    
        }
    
        NSLog(@"%d, %@", f, newString);
    }
    

2 个答案:

答案 0 :(得分:5)

最简单的方法是autorelease

NSString *newString = [[[NSString alloc] initWithFormat:@"Data: "] autorelease]; 

或者在上面公布的特定情况下:

NSString *newString = @"Data: "; 

答案 1 :(得分:2)

stringByAppendingFormat会返回一个新的autoreleased字符串。原始newString未发布。 最好使用NSMutableStringappendFormat

for(int j = 1; j < [smokeArray count]; j++) {

    NSMutableString *newString = [[NSMutableString alloc] initWithString:@"Data: "]; 
    int f = [[[smokeArray objectAtIndex:j] num] intValue];

    for (int i = 0; i<6; i++) {
        int d = [[[[smokeArray objectAtIndex:j] dat] objectAtIndex:i] intValue];

        if ( d > 0) {  [newString appendFormat:@"-%d",d];   } // fixed a potential logic error ( i > 0 )
        else { [newString appendFormat:@"%d",d];  }

    }

    NSLog(@"%d, %@", f, newString);
    // Do something useful like set a label or property with the string
    [newString release];
}