开发者社区> 问答> 正文

尝试一对多添加对象-核心数据关系时出现“无法转换类型的值”错误-SwiftUI

每次我尝试运行这个,我都会得到一个“无法将‘GAME_Detail.Goal’(0x6000012c8bb0)类型的值转换为”GAME_Detail.GAME“(0x1099492e0)。2019-12-23 17:47:41.396652-0600游戏详细信息[14958:463279]无法将‘GAME_Detail.Goal’(0x6000012c8bb0)类型的值转换为”Game1099492e0“类型。”错误。

我试图通过CoreData的一对多关系方面来学习和工作,但这是一次旅程。

好主意当我在游戏类中添加一个游戏时,我将进入游戏细节,并希望添加一个游戏目标。当我试图通过AddGameGoalsView.Swiver添加目标时,它会导致应用程序崩溃,并出现“无法转换类型值”的错误。

我认为我的问题是让ManagedObjectContext访问游戏并将值保存到GateArray中(在GAME+CoreDataProperties.Swive中描述)。

提前谢谢!

核心数据中的游戏模型xcdatamodeld:picture of game model in Core Data

核心数据中的目标模型xcdatamodeld:picture of goal model in Core Data

GameGoalsDetail.swift

import SwiftUI import CoreData

struct GameGoalsDetail: View { @Environment(.managedObjectContext) var moc @FetchRequest(entity: Game.entity(), sortDescriptors: []) var games: FetchedResults

@State private var showingAddGoal = false

@State private var goalComplete = false

let game: Game

var body: some View {
    VStack {
        Text(self.game.wrappedGameName)
        ForEach(game.goalArray, id: \.self)  { goal in
            Text(goal.wrappedGoalName)
            }

        Button("Add Game Goal") {
            self.showingAddGoal.toggle()
        }
            .sheet(isPresented: $showingAddGoal) {
                AddGameGoalsView().environment(\.managedObjectContext, self.moc)
        }
    }
}

} #if DEBUG struct GameGoalsDetail_Previews: PreviewProvider { static var previews: some View { let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext let newGame = Game.init(context: context) newGame.gameName = "Apex Legends" newGame.gameDescription = "Maybe this will work" newGame.goal = ["Goal 1", "Goal 2"] return GameGoalsDetail(game: newGame).environment(.managedObjectContext, context) } } #endif

AddGameGoalsView.swift

import SwiftUI import CoreData

struct AddGameGoalsView: View { @Environment(.managedObjectContext) var moc @FetchRequest(entity: Game.entity(), sortDescriptors: []) var games: FetchedResults @Environment(.presentationMode) var presentationMode

@State private var goalName = ""


var body: some View {
    NavigationView {
        Form {
            VStack {
                TextField("Add Game Goal", text: $goalName)
            }
            HStack {
                Spacer()
                Button("Add Goal") {
                    let newGoal = Goal(context: self.moc)
                    newGoal.goalName = self.goalName
                    newGoal.goalComplete = false
                    newGoal.goalOfGame? = Game(context: self.moc)

                    do {
                        try self.moc.save()
                        self.presentationMode.wrappedValue.dismiss()

                    } catch {
                        print("Whoops! \(error.localizedDescription)")
                    }
                }
            }
        }
        .navigationBarTitle("Add Game Goal")
    }
}

} ContentView.swift

import SwiftUI
import CoreData


struct ContentView: View {
    @Environment(\.managedObjectContext) var moc
    @FetchRequest(entity: Game.entity(), sortDescriptors: [NSSortDescriptor(keyPath: \Game.gameName, ascending: true)]) var games: FetchedResults<Game>
    @State private var showingAddGame = false

    var body: some View {
        NavigationView {
            List {
                ForEach(games, id: \.self) { games in
                    NavigationLink(destination: GameGoalsDetail(game: games)) {
                        VStack(alignment: .leading) {
                            Text(games.gameName ?? "Unknown Game")
                                .font(.title)
                            Text(games.gameDescription ?? "Unknown Game Description")
                                .font(.subheadline)
                        }
                    }
                }
            .onDelete(perform: removeGames)
            }
            .navigationBarTitle("Game Goals")
            .navigationBarItems(leading: EditButton(), trailing: Button("Add") {
                self.showingAddGame.toggle()
            })
                .sheet(isPresented: $showingAddGame) {
                    AddGameView().environment(\.managedObjectContext, self.moc)
            }
        }
    }

    func removeGames(at offsets: IndexSet) {
        for index in offsets {
            let game = games[index]
            moc.delete(game)
        }
        try? moc.save()
    }
}

#if DEBUG
struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        return ContentView().environment(\.managedObjectContext, context)
    }
}
#endif

游戏+CoreDataClass.斯威夫特

import Foundation
import CoreData

@objc(Game)
public class Game: NSManagedObject {

}

游戏+CoreDataProperties.Swive

import CoreData


extension Game {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Game> {
        return NSFetchRequest<Game>(entityName: "Game")
    }

    @NSManaged public var gameDescription: String?
    @NSManaged public var gameName: String?
    @NSManaged public var goal: NSSet?

    public var wrappedGameName: String {
        gameName ?? "Unknown Game"
    }

    public var wrappedGameDescription: String {
        gameDescription ?? "Unknown Game Description"
    }

    public var goalArray: [Goal] {
        let set = goal as? Set<Goal> ?? []

        return set.sorted {
            $0.wrappedGoalName < $1.wrappedGoalName
        }
    }

}

// MARK: Generated accessors for goal
extension Game {

    @objc(addGoalObject:)
    @NSManaged public func addToGoal(_ value: Goal)

    @objc(removeGoalObject:)
    @NSManaged public func removeFromGoal(_ value: Goal)

    @objc(addGoal:)
    @NSManaged public func addToGoal(_ values: NSSet)

    @objc(removeGoal:)
    @NSManaged public func removeFromGoal(_ values: NSSet)

}

目标+CoreDataProperties.Swive

import Foundation
import CoreData


extension Goal {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Goal> {
        return NSFetchRequest<Goal>(entityName: "Goal")
    }

    @NSManaged public var goalName: String?
    @NSManaged public var goalComplete: Bool
    @NSManaged public var goalOfGame: Game?

    public var wrappedGoalName: String {
        goalName ?? "Unknown Goal"
    }

}

乐意提供任何额外的数据或想法。只是试着学习和坚持。我从许多核心数据中得到的一对多的信息hackingwithswift.com或者疯狂地谷歌。

展开
收起
游客5akardh5cojhg 2019-12-24 13:09:59 1119 0
0 条回答
写回答
取消 提交回答
问答地址:
问答排行榜
最热
最新

相关电子书

更多
继承与功能组合 立即下载
对象的生命期管理 立即下载
HBase2.0重新定义小对象实时存取 立即下载