0

此代码在某些时候有效,但有时会因 EXC_BAD_ACCESS 错误而崩溃。

NSInteger compareDistance(id num1, id num2, void *context) 
{
    int rv;
    //cast parameters from general type
    CLLocation* location = (__bridge_transfer CLLocation *)context;
    Attraction* attr1 = num1;
    Attraction* attr2 = num2;

    //convert to CLLocation objects and calculate distance from user current
    CLLocation* locationAttr1 = 
    [[CLLocation alloc] initWithLatitude:attr1.latitude 
                               longitude:attr1.longitude];
    CLLocation* locationAttr2 = 
    [[CLLocation alloc] initWithLatitude:attr2.latitude 
                               longitude:attr2.longitude];
    CLLocationDistance distance1 = [locationAttr1 distanceFromLocation:location];
    CLLocationDistance distance2 = [locationAttr2 distanceFromLocation:location];

    //compare and rate
    if (distance1 < distance2)
        rv = NSOrderedAscending;
    else if (distance1 > distance2)
        rv = NSOrderedDescending;
    else
        rv = NSOrderedSame;

    return rv;
}

这是一个用于排序的比较函数NSMutableArray

-(NSMutableArray *)getAttractionsByDistanceInCategory:(int)catID
{
    [self confirmAttractions];

    //set up array and context to prepare for sort
    NSMutableArray *attractionsToSort = [[NSMutableArray alloc] init];
    for (Attraction *a in attractions)
    {
        if ((catID < 0) || (catID >= 0 && a.category == catID))
            [attractionsToSort addObject:a];
    }

    CLLocation* currentLocation = 
        [[CLLocation alloc] initWithLatitude:usersLat longitude:usersLng];

    //conduct sort
    [attractionsToSort sortUsingFunction:compareDistance
                                 context:(__bridge_retained void *)currentLocation];

    return attractionsToSort;
}

唔。您认为问题可能出在 ARC 上吗?我正在关注那项__bridge_retained void *业务。

提前感谢您的任何建议!

4

1 回答 1

3

__bridge_transfer将所有权转移到目标对象,这可能不是您想要在此处执行的操作,您不想要.context要做到这一点。

基本上,您不想将所有权转移到任何地方,因此只需__bridge在两种情况下都使用它,它应该可以正常工作。

于 2012-05-02T03:32:14.110 回答