问题描述
如何防止将重复项添加到RealmSwift
中的列表?
How do I prevent adding duplicates to a list in RealmSwift
?
我将我的User
作为领域对象,但是真正的数据源是服务器(只需使用Realm在本地缓存用户).当我从服务器获取当前用户数据时,我想确保存储在领域中的用户具有来自服务器的所有播放列表(以及它们的曲目等同步列表).我担心如果我从服务器上遍历这些列表,并追加到myUser.playlists
,最终可能会多次将相同的播放列表添加到用户的播放列表中.
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"
}
}
推荐答案
这取决于来自服务器的数据类型.如果整个播放列表数据总是来了(您可以随时替换现有的播放列表数据),则只需将列表删除为空,然后追加即可.
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)
}
}
这篇关于如何防止RealmSwift列表中出现重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!