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

前端 未结 4 454
我寻月下人不归
我寻月下人不归 2020-12-24 12:23

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

相关标签:
4条回答
  • 2020-12-24 12:30

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

    @"firstName BEGINSWITH[c] $FIRST_NAME"
    
    0 讨论(0)
  • 2020-12-24 12:31

    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:)];
    
    0 讨论(0)
  • 2020-12-24 12:42

    Swift Version:

    let sortDescriptor = NSSortDescriptor(key: "firstName", ascending: true, selector: #selector(NSString.localizedCaseInsensitiveCompare))
    
    0 讨论(0)
  • 2020-12-24 12:55

    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.

    0 讨论(0)
提交回复
热议问题