我使用coredata,所以我需要我的实体的排序描述符
例如,Coordinate-entity有这个类func:
class func sortDescriptors() -> Array<NSSortDescriptor> { return [NSSortDescriptor(key: "sequence",ascending: true)] }
当我对CoreData执行提取请求时,我正在使用它:
var request = NSFetchRequest(entityName: entityName) request.sortDescriptors = T.sortDescriptors()
但是,当我有一个坐标数组作为另一个coredata对象的属性时,这是一个NSSet(即未排序的)
为了解决这个问题,我正在返回这样的坐标:
return NSArray(array: coordinates!).sortedArrayUsingDescriptors(Coordinate.sortDescriptors()) as? Array<Coordinate>
哪个觉得丑陋,要使用NSArray来获取sortedArrayUsingDescriptors方法.有一种类似的方法可以直接在Swift数组上执行.阵列<坐标>通过使用排序描述符?
谢谢!
解决方法
没有内置的方法,但您可以使用协议扩展添加它们:
extension MutableCollectionType where Index : RandomAccessIndexType,Generator.Element : AnyObject { /// Sort `self` in-place using criteria stored in a NSSortDescriptors array public mutating func sortInPlace(sortDescriptors theSortDescs: [NSSortDescriptor]) { sortInPlace { for sortDesc in theSortDescs { switch sortDesc.compareObject($0,toObject: $1) { case .OrderedAscending: return true case .OrderedDescending: return false case .OrderedSame: continue } } return false } } } extension SequenceType where Generator.Element : AnyObject { /// Return an `Array` containing the sorted elements of `source` /// using criteria stored in a NSSortDescriptors array. @warn_unused_result public func sort(sortDescriptors theSortDescs: [NSSortDescriptor]) -> [Self.Generator.Element] { return sort { for sortDesc in theSortDescs { switch sortDesc.compareObject($0,toObject: $1) { case .OrderedAscending: return true case .OrderedDescending: return false case .OrderedSame: continue } } return false } } }
但是请注意,只有当数组元素是类而不是结构时,这将起作用,因为NSSortDescriptor compareObject方法需要符合AnyObject的参数
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。