开发者

Object leaked... how can i solve it?

开发者 https://www.devze.com 2023-01-12 18:50 出处:网络
When i do \"Build and analyze\" xCode gives me the following warning: Potential leak of an object allocated on line 70

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


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


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

精彩评论

暂无评论...
验证码 换一张
取 消