使用NSSortDescriptors,返回的数组为null

时间:2013-01-10 13:47:34

标签: iphone sorting nssortdescriptor

借助于StefanB在How to sort NSMutableArray using sortedArrayUsingDescriptors?中的回答,我得到了很多了解,并且在我的项目中实现了NSSortDescriptors,我有来自Facebook Graph的Facebook Places名称,描述,id,long和lat。然后使用我的位置和来自Facebook Places的长距离计算距离。并将所有这些保存在字典的数组(placesDataArray)中。

现在问题是在尝试对此数组(placesDataArray)进行排序时,返回数组(sortedArray)是否为空?

 NSLog(@"PLACES DATA ARRAY ===== > %@", placesDataArray);

    NSSortDescriptor * distanceDescriptor = [[NSSortDescriptor alloc] initWithKey:DISTANCE
                                                                         ascending:YES];

    id obj;
    NSEnumerator * enumerator = [placesDataArray objectEnumerator];
    while ((obj = [enumerator nextObject]));

    NSArray * descriptors =
    [NSArray arrayWithObjects:distanceDescriptor, nil];
    NSArray * sortedArray =
    [placesDataArray sortedArrayUsingDescriptors:descriptors];

    NSLog(@"\nSorted =========================>");

    enumerator = [sortedArray objectEnumerator];
    while ((obj = [enumerator nextObject]));
    NSLog(@"SORTED ARRAY ===========> \n%@", obj);

我的结果是:

> 2013-01-10 18:50:40.439 Chat.Points[12091:c07] PLACES DATA ARRAY ===== > (
        {
        category = Hotel;
        distance = "0.109";
        name = "New York Marriott Marquis";
        placeImageString = 20372413613;
    },
        {
        category = Hotel;
        distance = "0.019";
        name = "DoubleTree Suites by Hilton New York City - Times Square";
        placeImageString = 85286252698;
    },
    .
    .
    .
    .
    .
        {
        category = "Local business";
        distance = "0.229";
        name = "Le Pain Quotidien";
        placeImageString = 153110388035573;
    },
        {
        category = "Local business";
        distance = "0.074";
        name = NYSC;
        placeImageString = 144712562228653;
    },
        {
        category = "Local business";
        distance = "0.193";
        name = "The W Hotel";
        placeImageString = 113613138695956;
    },
        {
        category = "Local business";
        distance = "0.015";
        name = "Palace Theatre - Pricilla Queen Of The Desert!";
        placeImageString = 130723233698153;
    },
        {


         category = Hotel;
            distance = "0.033";
            name = "Renaissance New York Times Square Hotel";
            placeImageString = 111789988858447;
        } ) 
2013-01-10 18:50:40.500 Chat.Points[12091:c07]  Sorted =========================> 
2013-01-10 18:50:44.993 Chat.Points[12091:c07] SORTED ARRAY ===========>  
(null)

请参阅我上面提供的链接中的问题。 非常感谢这项努力。

2 个答案:

答案 0 :(得分:3)

打印'sortedArray'而不是'obj'

错误 - >

NSLog(@"SORTED ARRAY ===========> \n%@", obj);

正确 - >

NSLog(@"SORTED ARRAY ===========> \n%@", sortedArray);

感谢https://stackoverflow.com/users/1187415/martin-r

答案 1 :(得分:2)

您正确排序数组,但在最终输出中打印错误的对象:

NSLog(@"SORTED ARRAY ===========> \n%@", obj);

应该是

NSLog(@"SORTED ARRAY ===========> \n%@", sortedArray);