ios - 排序核心数据

标签 ios core-data

我有一些字符串和整数混合的数据,

"003G"
"002P"
"001P"
"018P"
"002G"
"019P"
"001G"
"020P"
"012P"
"011P"
"012G"
"013P"
"007P"
"011G"
"010P"
"009P"
"008P"
"005P"
"006P"
"014P"
"007G"
"010G"
"009G"
"008G"
"015P"
"006G"
"005Ga"
"004P"
"016P"
"005G"
"004G"
"003P"
"017P"

需要像这样的输出:
"001P"
"002P"
"003P"
"004P"
"005P"
"006P"
"007P"
"008P"
"009P"
"010P"
"011P"
"012P"
"013P"
"014P"
"015P"
"016P"
"017P"
"018P"
"019P"
"020P"
"001G"
"002G"
"003G"
"004G"
"005G"
"005Ga"
"006G"
"007G"
"008G"
"009G"
"010G"
"011G"
"012G"

同时Android使用*[0-9,0P-9P,0G-9G]进行了排序

最佳答案

这是一个非常不寻常的排序顺序。您必须使用Comparator编写自定义描述符

需要两个描述符。

  • 排序第四个字符降序
    let sortDescriptor1 = NSSortDescriptor(key: "referenceNo", ascending: false) { (obj1, obj2)  -> ComparisonResult in
        let string1 = obj1 as! String
        let string2 = obj2 as! String
        let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
        let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
        return String(string1[fourthChar1]).compare(String(string2[fourthChar2]))
    }
    
  • 使用numeric选项对前3个字符进行升序排序,并考虑xxxxa的大小写
    let sortDescriptor2 = NSSortDescriptor(key: "referenceNo", ascending: true) { (obj1, obj2)  -> ComparisonResult in
        let string1 = obj1 as! String
        let string2 = obj2 as! String
        let fourthChar1 = string1.index(string1.startIndex, offsetBy: 3)
        let fourthChar2 = string2.index(string2.startIndex, offsetBy: 3)
        let orderedResult = string1.substring(to: fourthChar1).compare(string2.substring(to: fourthChar2), options: .numeric)
        if orderedResult == .orderedSame {
            return string1.characters.count < string2.characters.count ? .orderedAscending : .orderedDescending
        } else {
            return orderedResult
        }
    }
    

  • 当然,这假定值是在ASCII范围内始终为4个字符或更多的字符串。

    关于ios - 排序核心数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44694471/

    相关文章:

    iphone - 我是否正确地向核心数据添加了一个对象?

    ios - complateTransition 不要关闭 View swift 2

    ios - BLE 设备应该在不扫描的情况下连接

    ios - 如何在具有多个分支的团队环境中处理核心数据模型版本控制

    iphone - 使用 NSPredicate 搜索 NSFetchedResultsController

    ios - 在 IOS 中获取 CoreData

    iphone - CBD Store 作为 iOS 中核心数据的持久存储

    ios - 如何使用 webview 在 Xamarin.iOS 中实现手动 Facebook 登录

    ios - TouchesBegan 在下一个 View Controller 中被识别

    ios - 使用 UIButton Action 在 UITableViewCell 中呈现一个弹出窗口