我已经在完成处理程序中创建了访存数据方法,并传递了两个参数搜索文本和fetchOfSet,但是我没有得到响应。我还必须对记录进行排序,并按降序过滤记录。
func fetchAllExpenses(searchText:String, page_no:Int,completionHandler: @escaping (_ responseHandler:[Expense]) -> Void, errorHandler: @escaping (_ error: Error) -> Void) {
var array = [Expense]()
// filter the id descending order
let idDescriptor: NSSortDescriptor = NSSortDescriptor(key: "exp_id", ascending: false)
// set the fetch limt data
fetchRequest.fetchLimit = 5
// sort the data by descending order
fetchRequest.sortDescriptors = [idDescriptor]
// need to update every time because can not predicate how many rows before fetched
fetchRequest.fetchOffset = page_no
do{
if let fetchResult = try context.fetch(fetchRequest) as? [Expense]{
for i in 0..<fetchResult.count {
let expenses: Expense? = fetchResult[i]
array.append(expenses!)
completionHandler(array)
}
DispatchQueue.main.async {
}
}else{
print("Not Found More Data")
}
} catch let error {
errorHandler("Error whilve retrieving data..\(error.localizedDescription)" as! Error)
}
}
答案 0 :(得分:0)
首先,核心数据的获取是同步的。不需要完成处理程序。
基本上缺少提取请求。而不是返回错误或可选将错误移交给调用者。如果未找到任何记录,则该数组为空。而且根本没有使用参数searchText
。
func fetchAllExpenses(pageNo: Int) throws -> [Expense] {
let fetchRequest : NSFetchRequest<Expense> = Expense.fetchRequest()
// filter the id descending order
let idDescriptor = NSSortDescriptor(key: "exp_id", ascending: false)
// set the fetch limt data
fetchRequest.fetchLimit = 5
// sort the data by descending order
fetchRequest.sortDescriptors = [idDescriptor]
// need to update every time because can not predicate how many rows before fetched
fetchRequest.fetchOffset = pageNo
return try context.fetch(fetchRequest)
}