问题
I want to sort the array with usernames that I retrieve from my core data. I retrieve it like this:
override func viewDidAppear(animated: Bool) {
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest(entityName: "User")
let en = NSEntityDescription.entityForName("User", inManagedObjectContext: context)
myList = context.executeFetchRequest(freq, error: nil)!
tv.reloadData()
}
And later I set the cells in my tableview like this:
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let CellID:NSString = "cell"
var cell: UITableViewCell = self.tv.dequeueReusableCellWithIdentifier(CellID) as UITableViewCell
if let ip = indexPath as Optional {
var data:NSManagedObject = myList[ip.row] as NSManagedObject
cell.textLabel!.text = data.valueForKeyPath("username") as String!
}
I tried to use the sorting function for in the viewDidAppear function like this:
var sortedList = myList.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }
But this gives me an error saying: "Could not find member 'localizedCaseInsensitiveCompare'"
Any suggestions on how to proceed would be appreciated.
回答1:
I like to use a separate function to fetch and sort the array. You sort the array by using an NSSortDescriptor
. You can add the capitalization check as a selector for the sort descriptor. I got the separate function idea from this tutorial. I used it and it works for me. I got the idea for the selector idea by referencing this Objective-C code.
var objectives: [NSManagedObject]!
func fetchUsernames() {
static let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context: NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest(entityName: "User")
let sortDescriptor = NSSortDescriptor(key: "username", ascending: true, selector: "localizedCaseInsensitiveCompare:")
freq.sortDescriptors = [sortDescriptor]
do {
let fetchedResults: [NSManagedObject] = try managedContext.executeFetchRequest(freq) as! [NSManagedObject]
if let results: [NSManagedObject] = fetchedResults {
objectives = results
}
} catch let error as NSError {
print("Error: \(error.localizedDescription)")
}
tableView.reloadData()
}
回答2:
executeFetchRequest
returns [AnyObject]?
and you need to convert this as [NSManagedObjet] array and sort on user
key
if let myList = myList as? [NSManagedObject] {
var sortedList = myList.sorted { ($0.valueForKeyPath("user") as String).localizedCaseInsensitiveCompare(($1.valueForKeyPath("user") as String)) == NSComparisonResult.OrderedAscending }
}
else {
println("My List not contains the NSManagedObject array")
}
来源:https://stackoverflow.com/questions/27649464/swift-sorting-an-array-retrieved-from-core-data