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
Method returns an Objective-C object with a +1 retain count (owning reference)
Looping back to the head of the loop
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];
}
精彩评论