views:

72

answers:

2

When i do "Build and analyze" xCode gives me the following warning:

Potential leak of an object allocated on line 70

  1. Method returns an Objective-C object with a +1 retain count (owning reference)

  2. Looping back to the head of the loop

  3. Object allocated on line 70 is no longer referenced after this point and has a retain count of +1 (object leaked)

This is the code (line 70 is the one that begins with "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);
}
+5  A: 

The simplest thing to do is to autorelease:

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

Or in the specific case as posted above simply:

NSString *newString = @"Data: "; 
Georg Fritzsche
Thnaks, this worked!
Abramodj
+2  A: 

stringByAppendingFormat returns a new autoreleased string. The original newString does not get released. You will be better off using NSMutableString and appendFormat.

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];
}
falconcreek
Thank you very much for your constructive answer! But please, edit it because it is not correct: the appendFormat method does not return a new string, it only modify the receiver. So:[newString appendFormat:@"%d",d];instead ofnewString = [newString appendFormat:@"%d",d];
Abramodj
Good catch. Removed the unnecessary re-assignment to newString. Using NSMutableString will reduce your overall memory footprint compared to creating new NSString instances with `stringWithFormat`.
falconcreek