iPhone CoreData - How to fetch managed objects, and sorting them ignoring case?

拥有回忆 提交于 2019-11-30 11:21:36

问题


Does anyone know how to fetch some results sorting them alphabetically but ignoring case?


回答1:


Thank you for your reply, but I need to sort the result of a simple "query" ignoring case. Your suggestion applies for searching and comparing.

SQL speaking, I need an ORDER BY firstName ASC, and this command must be case insensitive for my usage.

I have done some Googling and I ended reading the NSSortDescriptor Class reference, and I could find the answer for my question. The solution is setting a selector to the sort descriptor as follow:

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES selector:@selector(caseInsensitiveCompare:)];

I hope it will be useful for more people.




回答2:


If the app is localized in several languages, please consider using the localizedCaseInsensitiveCompare: selector instead of caseInsensitiveCompare. It will have the effect to avoid the letter 'é' to be after the letter 'e'.

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)];



回答3:


Check out the NSPredicate programming guide, but basically use [c] to ignore case:

@"firstName BEGINSWITH[c] $FIRST_NAME"



回答4:


Swift Version:

let sortDescriptor = NSSortDescriptor(key: "firstName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare))


来源:https://stackoverflow.com/questions/2013158/iphone-coredata-how-to-fetch-managed-objects-and-sorting-them-ignoring-case

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!