Abramodj
Abramodj

Reputation: 5879

Object leaked... how can i solve it?

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);
}

Upvotes: 1

Views: 640

Answers (2)

falconcreek
falconcreek

Reputation: 4170

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];
}

Upvotes: 2

Georg Fritzsche
Georg Fritzsche

Reputation: 99074

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: "; 

Upvotes: 5

Related Questions