按日期获取最后25个CoreData条目

时间:2015-08-24 16:21:11

标签: ios swift core-data

我有一个核心数据实体:

@objc(Messages)
class Messages: NSManagedObject {

     @NSManaged var receiver: String?
     @NSManaged var time: NSDate?
     @NSManaged var message: String?
}

我用var time = NSDate()

保存时间

我尝试获取这样的数据:

func fetchData(limit: Int, sort: Bool, sorter: String) -> Array<AnyObject> {
    let freq = NSFetchRequest(entityName: self.coreDataEntity)
    freq.fetchLimit = limit
    if sort == true {
        freq.sortDescriptors = [NSSortDescriptor(key: sorter, ascending: false)]
    }
    do {
        try self.fetchArray = context.executeFetchRequest(freq)
    } catch let error as NSError {
        print("CoreData - Fehler (fetch): \(error.localizedDescription)")
    }

    fetchArray.reverse()
    return fetchArray!
}

我想要的是最后25个条目。最新的条目应该是数组中的最后一个。

我称之为:

var messages:Array<AnyObject> = []
...
self.messages = fetchData(25, sort: true, sorter: "time")

fetchArray.reverse()无所作为

1 个答案:

答案 0 :(得分:0)

反向以相反顺序返回由元素组成的数组,它不会重新排列现有数组中的项。只需修改为:

let newArray = fetchArray.reverse()
fetchArray = newArray
return fetchArray!