Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

swift - Create array of other model with Realm - SwiftUI

I have two models that I want to store in a realm database. They are team and player. Each team will have x number of players and I want these to be accessible through the team. E.g. the user selects a team and then any corresponding players. I want the user in the end to be able to create a new team, create new players and assign players to a team

class Team: Object{
    @objc dynamic var teamName: String = ""
    @objc dynamic var players: [Player] = []
}

class Player: Object{
    @objc dynamic var playerName: String = ""
    @objc dynamic var shirtNumber: Int = 0
}

How would I then look at accessing these new models and more specifically, what would be a good way of iterating through the teams, and then the players inside.

I am very new to Realm and the concepts of databases inside my app so not really sure where to start


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First you want to leverage a List object instead of an array to store players in a team:

class Team: Object{
    @objc dynamic var teamName: String = ""
    let playerList = List<Player>()
}

that will create a one to many relationship (one team has many players).

If you need to traverse from player back to team you can either manually do it with a direct relationship

class Player: Object{
    @objc dynamic var playerName: String = ""
    @objc dynamic var shirtNumber: Int = 0
    @objc dynamic var myTeam: Team!
}

or you can have Realm manage it for you and automatically create the inverse relationship*

class Player: Object{
    @objc dynamic var playerName: String = ""
    @objc dynamic var shirtNumber: Int = 0
    var teams = LinkingObjects(fromType: Team.self, property: "playerList")
}

As far as iterating over the teams and players, just a simple for loop will do it

let teamResults = realm.objects(Team.self)

for team in teamResults {
   print(team.teamName)
   for player in team.playerList {
       print("  player: (player.playerName)"
   }
}

*note that LinkingObjects is plural. It actually creates a many to many relationship - that means a player could be linked back to several teams. This generally isn't an issue and more a design choice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...