Jinu
Jinu

Reputation: 8675

Sorting Core Data

I have some data with mixed of String and Integer like,

"003G"
"002P"
"001P"
"018P"
"002G"
"019P"
"001G"
"020P"
"012P"
"011P"
"012G"
"013P"
"007P"
"011G"
"010P"
"009P"
"008P"
"005P"
"006P"
"014P"
"007G"
"010G"
"009G"
"008G"
"015P"
"006G"
"005Ga"
"004P"
"016P"
"005G"
"004G"
"003P"
"017P"

Need output like :

"001P"
"002P"
"003P"
"004P"
"005P"
"006P"
"007P"
"008P"
"009P"
"010P"
"011P"
"012P"
"013P"
"014P"
"015P"
"016P"
"017P"
"018P"
"019P"
"020P"
"001G"
"002G"
"003G"
"004G"
"005G"
"005Ga"
"006G"
"007G"
"008G"
"009G"
"010G"
"011G"
"012G"

Same time Android done the sorting with *[0-9,0P-9P,0G-9G]

Upvotes: 1

Views: 194

Answers (3)

vadian
vadian

Reputation: 285064

That's a very unusual sorting order. You have to write custom descriptors using a Comparator

Two descriptors are needed.

  1. Sort the fourth character descending

    let sortDescriptor1 = NSSortDescriptor(key: "referenceNo", ascending: false) { (obj1, obj2)  -> ComparisonResult in
        let string1 = obj1 as! String
        let string2 = obj2 as! String
        let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
        let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
        return String(string1[fourthChar1]).compare(String(string2[fourthChar2]))
    }
    
  2. Sort the first 3 characters ascending with numeric option and consider the xxxxa case

    let sortDescriptor2 = NSSortDescriptor(key: "referenceNo", ascending: true) { (obj1, obj2)  -> ComparisonResult in
        let string1 = obj1 as! String
        let string2 = obj2 as! String
        let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
        let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
        let orderedResult = string1.substring(to: fourthChar1).compare(string2.substring(to: fourthChar2), options: .numeric)
        if orderedResult == .orderedSame {
            return string1.characters.count < string2.characters.count ? .orderedAscending : .orderedDescending
        } else {
            return orderedResult
        }
    }
    

Of course this assumes that the values are strings with always 4 characters and more in the ASCII range.

Upvotes: 3

Vinit Ingale
Vinit Ingale

Reputation: 401

If you are using NSFetchRequest to query core data, then go ahead and add sort descriptor on fetchRequest like below :

fetchRequest.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"referenceNo" ascending:YES selector:@selector(caseInsensitiveCompare:)]];

Upvotes: 0

Saranjith
Saranjith

Reputation: 11567

NSArray *keysArray;  // your strings

Put every strings into an array and use code below

NSArray *sortedArray = [keysArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Apple provides several selectors for alphabetic sorting:

compare:
caseInsensitiveCompare:
localizedCompare:
localizedCaseInsensitiveCompare:
localizedStandardCompare:

Upvotes: 0

Related Questions