如何根据查找具有特定值的实体在我的核心数据之间进行迭代
Posted
技术标签:
【中文标题】如何根据查找具有特定值的实体在我的核心数据之间进行迭代【英文标题】:How do iterate between my core data depending to find entities with a particular value 【发布时间】:2020-06-30 15:51:28 【问题描述】:我是 swift 的初学者。我有一个名为 Task 的 coredata 实体,其属性为 Date。我想在该实体中的所有 nsmanaged 对象之间进行迭代,并提取具有特定日期的对象并将它们放入一个数组中。
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)")
我试过了,但我到处都遇到语法错误。
【问题讨论】:
请在您的问题中粘贴错误。 【参考方案1】:有几个问题
替换
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)")
并且始终以单数形式命名 Core Data 实体 (Task
)。
【讨论】:
谢谢你我做到了。在 item.value(forKey: "date") 中获取日期。这条线现在给我一个错误。 “For-in 循环需要‘任何?’符合'Sequence';你的意思是解开可选的吗?" 你必须投类型,请仔细阅读我的回答。并且不要使用value(forKey
anyway。使用更好的语法。以上是关于如何根据查找具有特定值的实体在我的核心数据之间进行迭代的主要内容,如果未能解决你的问题,请参考以下文章