Zerium
Zerium

Reputation: 17333

How to sort Core Data using the last name, with only a full name available?

I have a fullName property in my Core Data entity Friends, which has values like:

I want to be able to extract the last name, and sort using these alphabetically, in Swift.

I currently only know how to sort using the full name, like so:

let sortDescriptor = NSSortDescriptor(key: "fullName", ascending: true)
request.sortDescriptors = [sortDescriptor]

Thanks.

Upvotes: 0

Views: 189

Answers (1)

Hitesh Surani
Hitesh Surani

Reputation: 13557

You can do as Follow.

1) Fetch all record from core data. (Suppose You have get aryFullname)

2) Using for loop you can get array only last name as follow.

//Define new mutable array aryfinalData
         for i in 0..<aryFullname.count
                {
                  var fullName = aryFullname.ObjectAtindex(i)
                  var fullNameArr = split(fullName) {$0 == " "}
                  var lastName: String? = fullNameArr.count > 1 ? fullNameArr[1] : nil
                  aryfinalData.addObject(lastName)
                 }

3) Sort Array as follow.

 //  convert NSMutableArray to the Array by using below line of code. 
    let arySort = aryfinalData as AnyObject as! [String]
    var sortedArray = arySort.sort { $0.name < $1.name }
 //  sortedArray is your Final array

Note: This is not a efficient solution but you don't have any solution and I am not sure about the above syntax so take care for the same and do changes if any require.

Upvotes: 0

Related Questions