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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…