简体   繁体   中英

Can I sort an XML-fed array with NSStrings as though some of them were numbers?

I'm using NSXMLParser to fetch a feed, and am sorting the resulting array according to various properties. Result of parse is a bunch of NSStrings. Everything is working fine, except of course the one string with numbers greater than 10 in it. Array ends up getting ordered like so:

9,8,7,6,5,4,3,2,1,12,11,10,0

Obviously I want it like so:

12,11,10,9,8,7,6,5,4,3,2,1,0

I'm assuming this is because NSStrings get sorted "alphabetically", and that I'm going to have to convert to NSNumber or something like it? Is this the best way, or is there something simpler?

I currently have:

if ([elementname isEqualToString:@"rankicon"])
{
    currentPlayer.rankicon = currentNodeContent;
}

and then:

NSSortDescriptor *rankDescriptor = 
    [[[NSSortDescriptor alloc]               
      initWithKey:@"rankicon" 
      ascending:NO]autorelease];

NSArray *sortDescriptors = 
    [NSArray arrayWithObjects:rankDescriptor, nil];

[players sortUsingDescriptors:sortDescriptors];

If you receive only numbers via xml then you can save them as NSNumbers instead.

NSString has also property intValue which returns that string as integer if it is possible.

这应该适用于您的情况(将selector作为参数添加到值localizedStandardCompare) -

NSSortDescriptor * rankDescriptor = [[[NSSortDescriptor alloc] initWithKey:@"rankicon"  ascending:NO selector:@selector(localizedStandardCompare:)] autorelease]; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM