Sorting NSString values as if NSInteger using NSSortDescriptor

前端 未结 7 1600
执念已碎
执念已碎 2020-11-28 09:10

I have created a sort descriptor to sort a plist response coming from my server. This works well with sort key having values upto 9. With more than 10 items I see abrupt res

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 10:04

    input

    {
        "seats": [{
            "seatNumber": "1"
        }, {
            "seatNumber": "10"
        }, {
            "seatNumber": "2"
        }]
    }
    

    sort using [NSSortDescriptor sortDescriptorWithKey:@"seatNumber" ascending:YES selector:@selector(localizedStandardCompare:)]]. The key is to use localizedStandardCompare. This will solve you problem.

    NSArray *seats = [self.seats sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"seatNumber" ascending:YES selector:@selector(localizedStandardCompare:)]]];
    

    output

    {
        "seats": [{
            "seatNumber": "1"
        }, {
            "seatNumber": "2"
        }, {
            "seatNumber": "10"
        }]
    }
    

    documentation: https://developer.apple.com/documentation/foundation/nsstring/1409742-localizedstandardcompare

提交回复
热议问题