根据今天的日期检查CoreData

时间:2020-01-05 15:16:45

标签: swift core-data swiftui

当CoreData记录的“ CreatedAt”属性(日期)与今天的日期匹配时,我试图在内容视图中隐藏“隐藏我”文本。

DiaryItem.swift

public class DiaryItem:NSManagedObject,Identifiable {
    @NSManaged public var createdAt:Date?
    @NSManaged public var title:String?
}

extension DiaryItem {
    static func getAllDiaryItems() -> NSFetchRequest<DiaryItem> {
       let request:NSFetchRequest<DiaryItem> = DiaryItem.fetchRequest() as!       NSFetchRequest<DiaryItem>

    let sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: true)

    request.sortDescriptors = [sortDescriptor]

    return request
    }
}

简化的 ContentView.swift

import SwiftUI
import CoreData

struct ContentView: View {

@Environment(\.managedObjectContext) var managedObjectContext

@FetchRequest(entity: DiaryItem.entity(), sortDescriptors: [
    NSSortDescriptor(keyPath: \DiaryItem.createdAt, ascending: false),
]) var diaryItems : FetchedResults<DiaryItem>

@State var show = false
@State private var showEntry: Bool = false

var body: some View {

        VStack {

            Text("Hide me!")

            List{

                ForEach(self.diaryItems) { diaryItem in

                    DiaryItemView(
                        title: diaryItem.title!,
                        createdAt: "\(diaryItem.createdAt!)",
                        diaryItem: diaryItem
                    )
                }
            }
        }
    }
}

我知道我可以比较如下所示的两个日期:

var first = Date()  

let isToday = Calendar.current.isDateInToday(first)

如何检查用户是否已经创建了一个CoreData记录,该记录的CreatedAt日期与当前日期匹配,并且是否隐藏了“隐藏我”文本?

感谢您阅读任何帮助,真是太神奇了!

1 个答案:

答案 0 :(得分:1)

如果您将Text("Hide me")替换为以下内容,则如果列表中的第一项(例如,您拥有ascending: false,则是最新的)位于今天:

if (diaryItems.first == nil || Calendar.current.isDateInToday(diaryItems.first!.createdAt!)) {
    Text("Hide me!")
    }

如果某些diaryItems的createdAt将来可能会变得更加复杂。