Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do i prevent duplicates in RealmSwift List?

How do I prevent adding duplicates to a list in RealmSwift?

I have my User as a realm object, but the real data source is a server (simply caching the user locally with 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 that their in sync wrt list of tracks and etc.). I'm worried that if i loop over those lists from the server, appending to myUser.playlists, that I may end up adding the same playlist to the user's list of playlists multiple 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"
    }
}
like image 447
Michael Avatar asked Jul 21 '16 20:07

Michael


People also ask

How do you prevent a list from duplication in Python?

The list count() method returns the number of occurrences of the value. We can use it with the remove() method to eliminate the duplicate elements from the list.


1 Answers

It depends on what kind of data coming from the server. If entire playlist data always come (you can always replace existing playlist data), you can just remove the list to empty, then append them.

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

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

If differential data coming from the server (also some are duplicated), you have to check whether the data already exists.

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)
    }
}
like image 136
kishikawa katsumi Avatar answered Oct 05 '22 23:10

kishikawa katsumi