如何在两个不同的表视图中设置两个类之间的Core Data关系。

huangapple go评论49阅读模式
英文:

how to set up a core data relationship between 2 classes with 2 different tableviews

问题

在我的Swift代码中,我有一个用于城市的类和一个用于州的类。州可以有多个城市,但一个城市只能属于一个州。我不确定是否正确设置了我的核心数据属性,特别是反向部分。我知道如何在属性面板上将其更改为一对多。我只是想知道是否漏掉了任何操作。当用户选择一个州时,它将跳转到一个新的类,在那里用户可以将城市保存到只属于该特定州的状态。

如何在两个不同的表视图中设置两个类之间的Core Data关系。

英文:

In my swift code I have one class for cities and one class for states. States can have many cities but a city can only have 1 state. I don't know if I set up my core data attributes correctly especially the inverse part. I know how to change it to one to many on the propties panel. I am just wondering if I am missing anything to do this. When the user selects a States it will go to a new class where the user can saves cities to only that specific state.

如何在两个不同的表视图中设置两个类之间的Core Data关系。

答案1

得分: 1

以下是翻译好的内容:

我在我的项目中已经做过这种类型的事情,但是虽然从我的角度来看,我没有清楚地理解你的问题,我可以说我在我的项目中所做的类似于以下内容:

State 实体: -

属性: -
stateN: 字符串

关系: -
city: 一对多关系(目标: 城市,反向: state)

City 实体: -

属性: -
cityN: 字符串

关系: -
state: 一对一关系(目标: State,反向: city)

现在,如果您想选择一个州并希望将一个城市保存到该特定州,请创建一个新的 City 实例,然后设置新城市的 cityN 属性。将新城市的 state 关系设置为所选的州。

let context = persistentContainer.viewContext

// 创建一个新的州
let state = State(context: context)
state.stateN = "Kerala"

// 创建一个新的城市
let city = City(context: context)
city.cityN = "Calicut"

// 将城市与州关联
city.state = state

// 保存更改
do {
    try context.save()
} catch {
    print("保存上下文时出错:\(error)")
}

请注意:上述代码是用 Swift 编写的,并假定您正在使用 Core Data 来管理数据。

英文:

I have done this type of things in my project, but I didn't understand your question clearly eventhough on my perspective I can say that like what I have done in my project

State entity:-

Attribute:-
stateN: String

Relationship:-
city: To-Many relationship (Destination: City, Inverse: state)

City entity:-

Attribute:-
cityN: String

Relationship:-
state: To-One relationship (Destination: State, Inverse: city)

and now if you want to selects a state and wants to save a city to that specific state.Create a new instance of City then Set the cityN attribute for new city.Set the state relationship of the new city to the selected state.

let context = persistentContainer.viewContext

// Create a new state
let state = State(context: context)
state.stateN = "Kerala"

// Create a new city
let city = City(context: context)
city.cityN = "Calicut"

// Associate the city with the state
city.state = state

// Save the changes
do {
    try context.save()
} catch {
    print("Error saving context: \(error)")
}

huangapple
  • 本文由 发表于 2023年6月9日 12:34:25
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437234.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定