本文介绍了如何根据查找具有特定值的实体在我的核心数据之间进行迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我是 swift 的初学者.我有一个名为 Task 的核心数据实体,其属性为 Date.我想在此实体中的所有 nsmanaged 对象之间进行迭代,并提取具有特定日期的对象并将它们放入数组中.
I'm a beginner to swift. I have a coredata entity named Task with an attribute Date. I want to iterate between all nsmanaged objects in this entity and extract the one with a particular date and put them in an array.
func loadTasks(){
let df = DateFormatter()
df.dateFormat = "dd-MM-yyyy" // assigning the date format
let now = df.string(from: Date()) // extracting the date with the given format
let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context: NSManagedObjectContext = appDel.persistentContainer.viewContext// handler to access the core date database by using the context from the app delegate loadTasks()
let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Tasks")
do {
coreTasks = try context.fetch(request) as! [NSManagedObject]
for item in coreTasks {
for date in item.value(forKey: "date"){
if (date == now) {
todaysTasks.append(date)
}
}
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
我试过了,但到处都是语法错误.
I tried this but i'm getting syntax error all over the place.
推荐答案
有几个问题
替换
for item in request {
for date in item.value(forKey: "date") {
if (date == now) {
与
for item in coreTasks {
if item.value(forKey: "date") as! String == now {
更好的语法是filter
记录
func loadTasks(){
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "dd-MM-yyyy" // assigning the date format
let now = df.string(from: Date()) // extracting the date with the given format
let appDel = UIApplication.shared.delegate as! AppDelegate
let context = appDel.persistentContainer.viewContext// handler to access the core date database by using the context from the app delegate loadTasks()
let request = NSFetchRequest<Tasks>(entityName: "Tasks")
do {
coreTasks = try context.fetch(request)
let todayItems = coreTasks.filter{$0.date == now}
todaysTasks.append(contentsOf: todayItems)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
还是应用谓词更好
func loadTasks(){
let df = DateFormatter()
df.locale = Locale(identifier: "en_US_POSIX")
df.dateFormat = "dd-MM-yyyy" // assigning the date format
let now = df.string(from: Date()) // extracting the date with the given format
let appDel = UIApplication.shared.delegate as! AppDelegate
let context = appDel.persistentContainer.viewContext// handler to access the core date database by using the context from the app delegate loadTasks()
let request = NSFetchRequest<Tasks>(entityName: "Tasks")
request.predicate = NSPredicate(format: "date == %@", now)
do {
todaysTasks = try context.fetch(request)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
并始终以单数形式命名核心数据实体(Task
).
And name Core Data entities always in singular form (Task
).
这篇关于如何根据查找具有特定值的实体在我的核心数据之间进行迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!