Best Method to handle FLAT-DATA

I am writing an app that will be deployed on AppleTV (for my own use only).
But tvOS does not support SQLite or any other form of local storage (and I don’t want to mess with iCloud). So my only resource is to store the data in the UserDefaults file.

The app will (on startup) read the data from there, and place it in an array, this array will be added to, updated, deleted from etc. On app shutdown, this data needs to be put back.

Here is the issue. I am giving each record a UID of some kind.

I guess I need to

  1. Delete from UserData all records where the UID is no longer in the Array
  2. Write back the contents of the Array (using the UID as the KEY to UserData). This will overwrite any previously existing record… and add any new UID record

Can anyone think of a better way?

No, though depending on the amount of data, it may be faster (and easier) to just delete all UserData and write the entire array back, instead of doing it piecemeal.

What I have done is given each record an “index” (from 1 to n)… just prior to writing the data back… each record has its index replaced so there are no gaps (in the case of deleted records).

So if I loaded 100 records … I would have read 1 to 100, if I delete 10 records, I resequence and write 1 to 90. the “count” is also written. So the data WILL contain dead records , but the count value makes sure none of those are read again. As the record count increases, they will begin overwriting the previous dead ones.

func LoadOptions() {
    dataStore.removeAll()
    if let _ = UserDefaults.standard as UserDefaults? {
        let count = getOption("showCount",0)
        sortKey   = getOption("sortKey",sortKey)
        if count>0 {
            for i in(1...count) {
                let temp = getOption("Show\(i)","")
                if temp != "" {
                    let v = Split(temp,"|")
                    dataStore.append(showRec(key:intVal(v[0]),name:v[1],service:v[2],day:intVal(v[3])))
                }
            }
        }
    } else {
        SaveOptions()
    }
}

func SaveOptions() {
    putOption("showCount",dataStore.count)
    putOption("sortKey",sortKey)
    if dataStore.count>0 {
        for i in(0...dataStore.count-1) {
            dataStore[i].key=(i+1)
            let temp="\(i+1)|\(dataStore[i].name)|\(dataStore[i].service)|\(dataStore[i].day)"
            putOption("Show\(i)",temp)
        }
    }
}