Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
720 views
in Technique[技术] by (71.8m points)

core data - iOS: natural sort order

I have an app for iOS that uses Core Data to save and retrieve data.
How would I fetch data sorted by a field of NSString type in natural sort order?

Right now the result is:

100_title
10_title
1_title

I need:

1_title
10_title
100_title
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use localizedStandardCompare: as selector in the sort descriptor for the Core Data fetch request, for example

NSSortDescriptor *titleSort = [[NSSortDescriptor alloc] initWithKey:@"title"
                                  ascending:YES 
                                   selector:@selector(localizedStandardCompare:)];
[fetchRequest setSortDescriptors:[titleSort]];

Swift 3:

let titleSort = NSSortDescriptor(key: "title",
                    ascending: true,
                    selector: #selector(NSString.localizedStandardCompare))
fetchRequest.sortDescriptors = [sortDescriptor]

or better

let titleSort = NSSortDescriptor(key: #keyPath(Entity.title),
                    ascending: true,
                    selector: #selector(NSString.localizedStandardCompare))
fetchRequest.sortDescriptors = [sortDescriptor]

where "Entity" is the name of the Core Data managed object subclass.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...