ios 为什么创建重复项而不是唯一的CoreData条目?

uemypmqf  于 2023-02-26  发布在  iOS
关注(0)|答案(1)|浏览(124)

我尝试在首次加载视图时将一些数据预加载到CoreData中,此时还没有任何条目,并且视图创建了正确的条目数,但随后它会将这些条目设置为相同的值(相同项目的重复)。这个想法是创建一个CoreData实体,预先加载用户可以在整个应用程序中获得的成就,它只会更新条目的“completed”属性。问题是,它创建了正确的条目数,但创建的都是一样的。下面是我目前拥有的:

import SwiftUI
import CoreData

struct AchievementView: View {
    
    @Environment(\.managedObjectContext) private var viewContext
    @FetchRequest(entity: Achievements.entity(), sortDescriptors: [
        NSSortDescriptor(key: "id", ascending: true)])
      private var achievements: FetchedResults<Achievements>

    var body: some View {
        NavigationView {
            ZStack {
                Color("Background")
                    .ignoresSafeArea(.all)
                VStack {
                    HStack {
                        let completedCount = achievements.filter(\.completed).count
                        let totalCount = achievements.count
                        let pctComp: Double = (Double(completedCount) / Double(totalCount)) * 100
                        
                        Image(systemName: "star.circle").padding(.leading, 5)
                            .foregroundColor(.secondary)
                        Text("Achievements".uppercased())
                            .fontWeight(.heavy)
                            .foregroundColor(.secondary)
                        Spacer()
                        Text("\(completedCount) OF \(totalCount) (\(pctComp, specifier: "%.f")%)")
                            .font(.system(size:16))
                            .fontWeight(.heavy)
                            .foregroundColor(.secondary)
                            .padding(.trailing, 10)
                    }
                    ScrollView(showsIndicators: false) {
                        VStack {
                            ForEach(achievements) { achievement in
                                HStack {
                                    VStack {
                                        if achievement.completed == false {
                                            Text(achievement.image ?? "")
                                                .padding()
                                                .grayscale(0.99)
                                                .overlay (
                                                    Circle()
                                                        .stroke(Color(.systemGray6), lineWidth: 2)
                                                ).padding()
                                        } else {
                                            Text(achievement.image ?? "")
                                                .padding()
                                                .overlay (
                                                    Circle()
                                                        .stroke(Color.green, lineWidth: 2)
                                                ).padding()
                                        }
                                    }
                                    VStack{
                                        if achievement.completed == false {
                                            HStack {
                                                Text(achievement.name ?? "")
                                                    .fontWeight(.heavy)
                                                    .foregroundColor(Color(.systemGray2))
                                                Spacer()
                                            }
                                            HStack {
                                                Text(achievement.desc ?? "")
                                                    .fontWeight(.light)
                                                    .font(.system(size:10))
                                                    .foregroundColor(Color(.systemGray2))
                                                Spacer()
                                            }
                                        } else {
                                            HStack {
                                                Text(achievement.name ?? "")
                                                    .fontWeight(.heavy)
                                                Spacer()
                                            }
                                            HStack {
                                                Text(achievement.desc ?? "")
                                                    .fontWeight(.light)
                                                    .font(.system(size:10))
                                                Spacer()
                                            }
                                        }
                                    }
                                    Spacer()
                                }   .background(Color("WeekShowBack"))
                                    .cornerRadius(15)
                            }
                        }
                    }
                }.padding()
            }
        }.navigationViewStyle(StackNavigationViewStyle())
            .onAppear(perform: loadAchievements)
    }
    
    private func loadAchievements() {
        
        print("Number of Times Called")
        let achievementNames = ["First Entry", "Movie Starter"]
        let achievemnetDesc = ["Enter your first movie or show", "Track 10 Movies"]
        let achievementComp = [false, false]
        let achievementImage = ["🥇","🔟"]
        
        if achievements.count == 0 {
            
            for index in 0..<achievementNames.count {
                let newAchievement = Achievements(context: self.viewContext)
                newAchievement.name = achievementNames[index]
                newAchievement.desc = achievemnetDesc[index]
                newAchievement.completed = achievementComp[index]
                newAchievement.image = achievementImage[index]
                
                do {
                    try viewContext.save()
                    print("Achievement Loaded!!!!!!")
                } catch let error {
                    print(error)
                }
            }
        }
    }
        
}

lc8prwob

lc8prwob1#

谢天谢地,我终于明白了!这简直要把我逼疯了,但我不知道这有什么关系,因为我以为CoreData会自动分配一个。不管怎样,我在函数的do语句中添加了这一行:

newAchievement.id = UUID()

现在它在CoreData中创建了正确的成果,现在我可以开始实际编码每个成果了。谢谢大家的帮助!

相关问题