In my
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
开发者_JS百科
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?
sDistance = [NSString stringWithFormat:@"(%.1f mi)",distance];
sDistance = @"";
In both lines sDistance
is 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.
NSString *sDistance; // alloc not required
Actually you are not using sDistance
anywhere. It does not look like that you need this.
精彩评论