我使用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的参数