根据日期和链接数据过滤 fetchRequest
Posted
技术标签:
【中文标题】根据日期和链接数据过滤 fetchRequest【英文标题】:Filter fetchRequest based on date and linked data 【发布时间】:2021-09-28 13:44:34 【问题描述】:我在 CoreData 中有 2 个数据表
锻炼:
extension Workout
@nonobjc public class func fetchRequest() -> NSFetchRequest<Workout>
return NSFetchRequest<Workout>(entityName: "Workout")
@NSManaged public var id: UUID?
@NSManaged public var name: String?
@NSManaged public var type: String?
@NSManaged public var notes: String?
@NSManaged public var created_at: Date?
@NSManaged public var updated_at: Date?
@NSManaged public var sessions: NSSet?
@NSManaged public var pinned: Bool
会话:
extension WorkoutSession
@nonobjc public class func fetchRequest() -> NSFetchRequest<WorkoutSession>
return NSFetchRequest<WorkoutSession>(entityName: "WorkoutSession")
@NSManaged public var created_at: Date?
@NSManaged public var id: UUID?
@NSManaged public var reps: Int16
@NSManaged public var sets: Int16
@NSManaged public var duration: Int64
@NSManaged public var updated_at: Date?
@NSManaged public var measurement: Double
@NSManaged public var notes: String?
@NSManaged public var type: Workout?
我想创建一个获取请求,以获取在某一天有会话的所有锻炼。
我现在要做的是单独获取所有的锻炼和课程。 让用户选择一个日期。 根据该日期过滤所有会话,映射会话以返回锻炼并使该数组独一无二。 哪个可行,但我想可能会更好。
@FetchRequest(entity: Workout.entity(), sortDescriptors: [NSSortDescriptor(key: "name", ascending: true)]) var fetchedWorkouts: FetchedResults<Workout>
@FetchRequest(entity: WorkoutSession.entity(), sortDescriptors: [NSSortDescriptor(key: "created_at", ascending: true)]) var sessions: FetchedResults<WorkoutSession>
@State private var day = Date()
var filteredList: [WorkoutSession]
return sessions.filter session in
Calendar.current.isDate(session.created_at ?? Date(), inSameDayAs:day)
var filteredWorkouts: [Workout]
let sessionsWithType = filteredList.filter session in
return session.type != nil
let uniqueWorkouts = Array(Set(sessionsWithType.map session in
return session.type!
))
return uniqueWorkouts.sorted workoutA, workoutB in
return workoutA.wrappedName < workoutB.wrappedName
我最终想要实现的是用户可以选择一天的视图。 然后,该应用程序将显示一个列表视图,该视图分为每个锻炼的部分,在这些部分中,您将看到您当天为该锻炼所做的会话。
例如:这些部分是单独的视图,用于获取所选日期的特定锻炼的会话。所以在这个主视图上,我只想要当天有课程的锻炼。
请让我知道您需要更多数据
【问题讨论】:
developer.apple.com/wwdc21/10017 【参考方案1】: self.date = date
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local
let startOfDay = calendar.startOfDay(for: date)
let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay)!
let workoutPredicate = NSPredicate(format: "SUBQUERY(sessions, $s, $s.created_at >= %@ AND $s.created_at < %@).@count > 0", argumentArray: [startOfDay,endOfDay])
self.workoutRequest = FetchRequest<Workout>(
entity: Workout.entity(),
sortDescriptors: [
NSSortDescriptor(key: "created_at", ascending: true)
],
predicate: workoutPredicate
)
【讨论】:
以上是关于根据日期和链接数据过滤 fetchRequest的主要内容,如果未能解决你的问题,请参考以下文章