Swift - 对从Core Data检索的数组进行排序

时间:2014-12-25 17:44:40

标签: ios arrays sorting core-data swift

我想用我从核心数据中检索的用户名对数组进行排序。我像这样检索它:

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()

}

后来我在我的tableview中设置了这样的单元格:

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!

    }

我尝试在viewDidAppear函数中使用sort函数,如下所示:

 var sortedList = myList.sorted { $0.localizedCaseInsensitiveCompare($1) == NSComparisonResult.OrderedAscending }

但是这给了我一个错误说:“找不到成员'localizedCaseInsensitiveCompare'”

有关如何继续的任何建议将不胜感激。

2 个答案:

答案 0 :(得分:2)

executeFetchRequest返回[AnyObject]?,您需要将其转换为[NSManagedObjet]数组并在user键上排序

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")
}

答案 1 :(得分:2)

我喜欢使用单独的函数来获取和排序数组。您使用NSSortDescriptor对数组进行排序。您可以将大小写检查添加为排序描述符的选择器。我从this tutorial得到了单独的函数构思。我用它,它对我有用。我通过引用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()
}