ios - Swift - 对从核心数据中检索到的数组进行排序

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

}

然后我像这样在我的表格 View 中设置单元格:

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’”

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

最佳答案

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

关于ios - Swift - 对从核心数据中检索到的数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27649464/

相关文章:

java - 在 android studio 中排序自定义对象的属性列表(API 级问题)

ruby-on-rails - Rails 4 : Sort by associated created_at if present, 否则由父级

java - 如何先按 x 然后按 y 对数组或 ArrayList<Point> ASC 进行排序?

ios - 在 iOS 8+ 设备中启动时状态栏看起来很奇怪(使用主从模板)

ios - 如何将 stackview 用于标签和文本字段,其中文本字段的长度更长

ios - 如何使用当前的 NSPersistentStore 方法在本地和 iCloud 中创建可共享的 Core Data .sqlite 备份

c - 使用指针将字符串数组传递给函数

php - Kirby CMS,如何使用 PHP 从对象中获取第一张图像?

c++ - ASCII 字符数组

ios - BLE 特性不一次读取完整字符串