Help with a leaky function
-(void)determineClosestLocationToUser:(NSArray *)allLocations
locationOfUser:(MapLocation *)userLocationIn
{
// Determine how many objects you have in the array (incase you'e too lazy to count, or changed the
// code to enter locations dynamically
NSUInteger counter = [allLocations count];
// set this value to the first item in the array, so it has something to compare to
closestLocationFound = [allLocations objectAtIndex:0];
// run a for l开发者_C百科oop to compare each of the locations in the array against the user location to determine
// which location is the closest
for(NSUInteger i = 0; i < counter; i++)
{
// setup 2 variables to hold the distances between the user and both locations for comparison
CLLocationDistance distance1 = 0;
CLLocationDistance distance2 = 0;
// create a CLLocation variable using the values from our MapLocation variable
// in order to utilize the getDistanceFrom function
CLLocation *user = [[CLLocation alloc] initWithLatitude:userLocationIn.coordinate.latitude longitude:userLocationIn.coordinate.longitude];
CLLocation *closest = [[CLLocation alloc] initWithLatitude:closestLocationFound.coordinate.latitude longitude:closestLocationFound.coordinate.longitude];
// create a variable to hold the values stores in the array
// (this should be accessed directly from the array, but I'm not sure how to do it yet - CHANGE THIS)
MapLocation *tempLoc = [[MapLocation alloc] init];
tempLoc = [allLocations objectAtIndex:i];
// create a CLLocation variable to hold the coordinates for each object in the array
// (has to be CLLocation for the getDistance from function to work)
CLLocation *check = [[CLLocation alloc] initWithLatitude:tempLoc.coordinate.latitude longitude:tempLoc.coordinate.longitude];
// get the distance from the current closest location
distance1 = [user getDistanceFrom:closest];
// now get the distance from the next location in the array
distance2 = [user getDistanceFrom:check];
// if the location we just checked is closer than the location we're currently storing
if(distance2 < distance1)
{
// declare that location the closest
closestLocationFound = [allLocations objectAtIndex:i];
}
// clean up
[user release];
[tempLoc release];
[check release];
[closest release];
}
}
I checked my code with the Leaks performance tool and it shows my app only has one leak (category:MapLocation , eventType: Malloc, size: 48, responsibleCaller:( ^ the above function) ) When I double click on the function it takes me to this line.
distance1 = [user getDistanceFrom:closest];
Any ideas or suggestions? Thanks in advance.
MapLocation *tempLoc = [[MapLocation alloc] init];
That's the line. You're alloc/init'ing a new MapLocation, and then immediately throwing it out
tempLoc = [allLocations objectAtIndex:i];
When this line executes, the original value of tempLoc
is leaked. That first line is useless and these should be combined in to
MapLocation *tempLoc = [allLocations objectAtIndex:i];
精彩评论