【问题标题】:Swift - Sorting an array retrieved from Core Data [duplicate]Swift - 对从核心数据检索到的数组进行排序
【发布时间】:2015-02-23 07:31:14
【问题描述】:

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

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

}

后来我像这样在我的表格视图中设置单元格:

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 函数中使用排序函数,如下所示:

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

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

任何关于如何进行的建议将不胜感激。

【问题讨论】:

  • 为什么不在获取请求中添加一个 sortDescriptor 呢?

标签: ios arrays sorting core-data swift


【解决方案1】:

我喜欢使用单独的函数来获取和排序数组。您可以使用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()
}

【讨论】:

    【解决方案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")
    }
    

    【讨论】:

    • 这给了我错误:“致命错误:无法从 Objective-C lldb 桥接数组”
    • 什么错误??您的 myList 应该只有 Strings 数组而不是用户数组或字典。请验证
    • myList 是一个 NSManagedObjects 数组,即 myList = context.executeFetchRequest(freq, error: nil)!
    • @frank21 我已经更新了答案,这将起作用看看
    • @codester 谢谢你,但现在我得到一个运行时错误:以 NSException 类型的未捕获异常终止。我不明白为什么会发生此错误,因为这通常发生在您没有正确引用对象时:/
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-05
    • 1970-01-01
    相关资源
    最近更新 更多