gpt4 book ai didi

swift - 如何使用完成处理程序在 core data swift 5 中获取过滤数据结果

转载 作者:行者123 更新时间:2023-11-30 10:44:36 25 4
gpt4 key购买 nike

我已经使用完成处理程序创建了获取数据方法,并传递了两个参数搜索文本和 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)
}
}

最佳答案

首先,核心数据获取是同步的。不需要完成处理程序。

基本上缺少获取请求。而不是返回错误或可选地将错误移交给调用者。如果没有找到记录,则数组为空。并且根本没有使用参数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)
}

关于swift - 如何使用完成处理程序在 core data swift 5 中获取过滤数据结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56016770/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com