W Dyson
W Dyson

Reputation: 4634

Using NSSortDescriptor to sort build numbers with Core Data

I'm trying to use NSSortDescriptor with Core Data to sort build numbers/software versions (NSStrings). The build numbers are actually just NSStrings but it seems to have a hard time with this. I'm guessing because of the multiple and irregular decimal points.

For example, I would like to sort the following.

1.7.6
1.8
1.6.2
1.9.0.1
2.0

Each line represents an NSString.

How would I do this properly or is there another way I should try?

Upvotes: 2

Views: 686

Answers (1)

Martin R
Martin R

Reputation: 539705

A sort descriptor using localizedStandardCompare: should produce the intended result:

[NSSortDescriptor sortDescriptorWithKey:@"buildNumber"
                              ascending:YES
                               selector:@selector(localizedStandardCompare:)];

localizedStandardCompare: is the "Finder-like" comparison and strings containing numbers are sorted according to their numerical value.

In Swift:

NSSortDescriptor(key: "buildNumber", ascending: true,
            selector: #selector(NSString.localizedStandardCompare))

Upvotes: 6

Related Questions