In my
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
I am calculating the distance between 2 points, so i have
NSString *sDistance = [[NSString alloc] init];
if (curLat != 0) {
if (curLong != 0) {
double desLat = [[requestedDict objectForKey:@"latitude"] doubleValue];
double desLong = [[requestedDict objectForKey:@"longitude"] doubleValue];
double distance = sqrt(69.1*(desLat-curLat)*69.1*(desLat-curLat)+69.1*(desLong-curLong)*cos(curLat/57.3)*69.1*(desLong-curLong)*cos(curLat/57.3));
sDistance = [NSString stringWithFormat:@"(%.1f mi)",distance];
[[cell distanceLabel] setText:[NSString stringWithFormat:@"(%.1f mi)",distance]];
}
else{
sDistance = @"";
[[cell distanceLabel] setText:@""];
}
}
[sDistance release];
When i do this, i get exc_bad_access errors, but when i change it to
NSString *sDistance = [[[NSString alloc] init] autorelease];
It works just fine. Don’t they do the same thing?
In both lines
sDistanceis pointing to a new string and so you are leaking the alloced string in the first line. When you send a autorelease message then it is added in autorelease pool and thus not leaked later. They are not same. When you alloc then you need to release that. Sending an autorelease message means the object is added to the autorelease pool and will be released later.You do not need this alloc here as you are creating autoreleased strings later. Just declare the string in first line. And also remove the
[sDistance release];in last line.Actually you are not using
sDistanceanywhere. It does not look like that you need this.