How to prevent duplication in the RealmSwift list?

How to prevent duplicates from being added to the list in RealmSwift?

I have Usera realm object, but the real data source is the server (just caching the user locally using Realm). When I get the current user data from my server, I want to make sure that my user stored in realm has all the playlists coming from the server (and their synchronization according to the list of tracks, etc.). I worry that if I go through these lists from the server by adding to myUser.playlists, I can end up adding the same playlist to the list of playlists several times.

class User: Object {
    
    dynamic var name = ""
    dynamic var id = ""
    let playlists = List<Playlist>()
    override class func primaryKey() -> String {
        return "id"
    }
}

class Playlist: Object {
    
    dynamic var name = ""
    dynamic var id = ""
    let tracks = List<Song>()
    override class func primaryKey() -> String {
        return "id"
    }
}

class Song: Object {
    
    dynamic var title = ""
    let artists = List<Artist>()
    dynamic var id = ""
    override class func primaryKey() -> String {
        return "id"
    }
}

class Artist: Object {
    dynamic var name = ""
    dynamic var id = ""
    override class func primaryKey() -> String {
        return "id"
    }
}
+5
3

, . ( ), , .

realm.write {
    user.playlists.removeAll() // empty playlists before adding

    for playlistData in allPlaylistData {
        let playlist = Playlist()
        ...
        user.playlists.append(playlist)
    }
}

, ( ), , .

realm.write {
    for playlistData in allPlaylistData {
        let playlist = Playlist()
        ...

        realm.add(playlist, update: true) // Must add to Realm before check

        guard let index = user.playlists.indexOf(playlist) else {
            // Nothing to do if exists
            continue
        }
        user.playlists.append(playlist)
    }
}
+10

.

  1. .
  2. .
  3. , .
0

@kishikava katsumi

for. , , user.playlists.contains(playlist)

Here is the code Thanks @kishikava katsumi for setting up.

let fetchedPlaylists: [Playlist] = ...

try! realm.write {
  realm.add(fetchedPlaylists, update: true)
  for playlist in fetchedPlaylists {
    guard !user.playlists.contains(playlist) else {
      continue
    }
    user.playlists.append(playlist)
  }
}
0
source

Source: https://habr.com/ru/post/1648704/


All Articles