Search code examples
swiftmodelsnscoding

Models with refference to another models - saving using NSCoding


I'm creating some kind of games tracker and want to ask if this kind of design is bad choice.

I'm using MVC architecture and inside my models I have refferences to other models, i.e. inside Player model I have

var name: String
var lastTimePlayed: Date?
var timesPlayed: Int
let playerID: String
var gamesPlayed = [Game]()
var matchesPlayed = [Game: [Match]]()
var gamesPlace = [Game: [Int]]()
var gamesPoints = [Game: [Int]]()

Here is and image of how it looks like:

Graph of all models used.

Arrows indicate that model keeps a refference to another model.

Would it be better to save just gameID and matchID or gameName instead of refferences to Game and Match models? It is easier for me to keep the direct refferences, so I can have access to dates of last matches etc. but I can do it the other way, too.

Of course, when I'm removing a model, I take care of all those refferences and remove them too, so there is no memory leak.

My second question is - will I have a problem when I try to save those using NSCoding (using NSKeyedArchiver.archiveRootObject at stores)? Won't it go in loop-like cycle going from Player to Game to Match and then to Player again?

Thank you for your help!


Solution

  • NSCoder subclasses know how to avoid circular references, see https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Archiving/Articles/archives.html.

    That said, you should probably look into introducing weak references into your data model to avoid retain cycles.