Avoid duplication in array of custom object in realm database. When Primary key is exist in the relational table only The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceRealm - Can't create object with existing primary key valueAndroid Realm Handling Primary Key in Relational Objectrealm swift . How to link to exist object with primary keyRealmList addAll duplicating object with same primary keyHow to conform to Codable and using Realm in swift 4 when class has a array of string?How to migrate multiple realm files in one AppHow to avoid duplicate entries of column in REALM database?How to do custom transformations using Codable?Realm - copy or primary key to avoid “object has been deleted or invalidated”Realm duplicate primary key crash with relationships

How did passengers keep warm on sail ships?

What is this lever in Argentinian toilets?

Can the prologue be the backstory of your main character?

How to pronounce 1ターン?

Mortgage adviser recommends a longer term than necessary combined with overpayments

Can a 1st-level character have an ability score above 18?

What was the last x86 CPU that did not have the x87 floating-point unit built in?

How to politely respond to generic emails requesting a PhD/job in my lab? Without wasting too much time

Relations between two reciprocal partial derivatives?

How to copy the contents of all files with a certain name into a new file?

How should I replace vector<uint8_t>::const_iterator in an API?

How does ice melt when immersed in water?

Difference between "generating set" and free product?

Can withdrawing asylum be illegal?

When did F become S in typeography, and why?

how can a perfect fourth interval be considered either consonant or dissonant?

How to test the equality of two Pearson correlation coefficients computed from the same sample?

system() function string length limit

How can I protect witches in combat who wear limited clothing?

Does Parliament need to approve the new Brexit delay to 31 October 2019?

Why can't devices on different VLANs, but on the same subnet, communicate?

How to delete random line from file using Unix command?

How do I add random spotting to the same face in cycles?

In horse breeding, what is the female equivalent of putting a horse out "to stud"?



Avoid duplication in array of custom object in realm database. When Primary key is exist in the relational table only



The 2019 Stack Overflow Developer Survey Results Are In
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
The Ask Question Wizard is Live!
Data science time! April 2019 and salary with experienceRealm - Can't create object with existing primary key valueAndroid Realm Handling Primary Key in Relational Objectrealm swift . How to link to exist object with primary keyRealmList addAll duplicating object with same primary keyHow to conform to Codable and using Realm in swift 4 when class has a array of string?How to migrate multiple realm files in one AppHow to avoid duplicate entries of column in REALM database?How to do custom transformations using Codable?Realm - copy or primary key to avoid “object has been deleted or invalidated”Realm duplicate primary key crash with relationships



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















how to avoid duplications in array of custom objects in realm Database, Below is my code and related JSON Please correct me if I do something wrong in the model.



JSON ->




"playlists": [

"id": "1f23bd3e-cc01-11e8-b25e-784f435e4a9a",
"name": "disney nostalgia",
"duration": 361,
,

"id": "2e1f0e02-cc05-11e8-9efe-784f435e4a9a",
"name": "songs from aladdin",
"duration": 331,

],
"tracks": [

"id": "3e986a2a-cc01-11e8-bb04-784f435e4a9a",
"name": "I'll Make a Man Out of You",
"artist": "Donny Osmond & Chorus"
,

"id": "aff8bcee-cc04-11e8-8c18-784f435e4a9a",
"name": "A Whole New World",
"artist": "Lea Salonga, Brad Kane"

]



and Models are as follow



class Songs: Object, Codable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()
enum CodingKeys: String, CodingKey
case playlists
case tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
playLists.forEach(self.playlists.append($0))

if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
tracksList.forEach(self.tracks.append($0))



func encode(to encoder: Encoder) throws
//



class Playlists: Object, Codable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0


enum CodingKeys: String, CodingKey
case id
case name
case duration


override static func primaryKey() -> String?
return "id"


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.duration = try container.decode(Int.self, forKey: .duration)



class Tracks: Object, Codable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0


enum CodingKeys: String, CodingKey
case id
case name
case artist


override static func primaryKey() -> String?
return "id"


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.artist = try container.decode(Int.self, forKey: .artist)




and this is how I save the data.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")



How to avoid duplications into the data when there is same response from server.










share|improve this question






















  • This will require using Set which is still under development. More info here:- github.com/realm/realm-java/issues/759 For now you have manually check before adding new items that your list don't contain the item you are trying to add.

    – Aks
    Mar 22 at 8:47

















0















how to avoid duplications in array of custom objects in realm Database, Below is my code and related JSON Please correct me if I do something wrong in the model.



JSON ->




"playlists": [

"id": "1f23bd3e-cc01-11e8-b25e-784f435e4a9a",
"name": "disney nostalgia",
"duration": 361,
,

"id": "2e1f0e02-cc05-11e8-9efe-784f435e4a9a",
"name": "songs from aladdin",
"duration": 331,

],
"tracks": [

"id": "3e986a2a-cc01-11e8-bb04-784f435e4a9a",
"name": "I'll Make a Man Out of You",
"artist": "Donny Osmond & Chorus"
,

"id": "aff8bcee-cc04-11e8-8c18-784f435e4a9a",
"name": "A Whole New World",
"artist": "Lea Salonga, Brad Kane"

]



and Models are as follow



class Songs: Object, Codable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()
enum CodingKeys: String, CodingKey
case playlists
case tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
playLists.forEach(self.playlists.append($0))

if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
tracksList.forEach(self.tracks.append($0))



func encode(to encoder: Encoder) throws
//



class Playlists: Object, Codable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0


enum CodingKeys: String, CodingKey
case id
case name
case duration


override static func primaryKey() -> String?
return "id"


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.duration = try container.decode(Int.self, forKey: .duration)



class Tracks: Object, Codable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0


enum CodingKeys: String, CodingKey
case id
case name
case artist


override static func primaryKey() -> String?
return "id"


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.artist = try container.decode(Int.self, forKey: .artist)




and this is how I save the data.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")



How to avoid duplications into the data when there is same response from server.










share|improve this question






















  • This will require using Set which is still under development. More info here:- github.com/realm/realm-java/issues/759 For now you have manually check before adding new items that your list don't contain the item you are trying to add.

    – Aks
    Mar 22 at 8:47













0












0








0








how to avoid duplications in array of custom objects in realm Database, Below is my code and related JSON Please correct me if I do something wrong in the model.



JSON ->




"playlists": [

"id": "1f23bd3e-cc01-11e8-b25e-784f435e4a9a",
"name": "disney nostalgia",
"duration": 361,
,

"id": "2e1f0e02-cc05-11e8-9efe-784f435e4a9a",
"name": "songs from aladdin",
"duration": 331,

],
"tracks": [

"id": "3e986a2a-cc01-11e8-bb04-784f435e4a9a",
"name": "I'll Make a Man Out of You",
"artist": "Donny Osmond & Chorus"
,

"id": "aff8bcee-cc04-11e8-8c18-784f435e4a9a",
"name": "A Whole New World",
"artist": "Lea Salonga, Brad Kane"

]



and Models are as follow



class Songs: Object, Codable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()
enum CodingKeys: String, CodingKey
case playlists
case tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
playLists.forEach(self.playlists.append($0))

if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
tracksList.forEach(self.tracks.append($0))



func encode(to encoder: Encoder) throws
//



class Playlists: Object, Codable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0


enum CodingKeys: String, CodingKey
case id
case name
case duration


override static func primaryKey() -> String?
return "id"


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.duration = try container.decode(Int.self, forKey: .duration)



class Tracks: Object, Codable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0


enum CodingKeys: String, CodingKey
case id
case name
case artist


override static func primaryKey() -> String?
return "id"


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.artist = try container.decode(Int.self, forKey: .artist)




and this is how I save the data.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")



How to avoid duplications into the data when there is same response from server.










share|improve this question














how to avoid duplications in array of custom objects in realm Database, Below is my code and related JSON Please correct me if I do something wrong in the model.



JSON ->




"playlists": [

"id": "1f23bd3e-cc01-11e8-b25e-784f435e4a9a",
"name": "disney nostalgia",
"duration": 361,
,

"id": "2e1f0e02-cc05-11e8-9efe-784f435e4a9a",
"name": "songs from aladdin",
"duration": 331,

],
"tracks": [

"id": "3e986a2a-cc01-11e8-bb04-784f435e4a9a",
"name": "I'll Make a Man Out of You",
"artist": "Donny Osmond & Chorus"
,

"id": "aff8bcee-cc04-11e8-8c18-784f435e4a9a",
"name": "A Whole New World",
"artist": "Lea Salonga, Brad Kane"

]



and Models are as follow



class Songs: Object, Codable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()
enum CodingKeys: String, CodingKey
case playlists
case tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
playLists.forEach(self.playlists.append($0))

if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
tracksList.forEach(self.tracks.append($0))



func encode(to encoder: Encoder) throws
//



class Playlists: Object, Codable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0


enum CodingKeys: String, CodingKey
case id
case name
case duration


override static func primaryKey() -> String?
return "id"


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.duration = try container.decode(Int.self, forKey: .duration)



class Tracks: Object, Codable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0


enum CodingKeys: String, CodingKey
case id
case name
case artist


override static func primaryKey() -> String?
return "id"


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
self.name = try container.decode(String.self, forKey: .name)
self.artist = try container.decode(Int.self, forKey: .artist)




and this is how I save the data.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")



How to avoid duplications into the data when there is same response from server.







ios swift realm realm-list






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 22 at 6:16









ChetanChetan

512712




512712












  • This will require using Set which is still under development. More info here:- github.com/realm/realm-java/issues/759 For now you have manually check before adding new items that your list don't contain the item you are trying to add.

    – Aks
    Mar 22 at 8:47

















  • This will require using Set which is still under development. More info here:- github.com/realm/realm-java/issues/759 For now you have manually check before adding new items that your list don't contain the item you are trying to add.

    – Aks
    Mar 22 at 8:47
















This will require using Set which is still under development. More info here:- github.com/realm/realm-java/issues/759 For now you have manually check before adding new items that your list don't contain the item you are trying to add.

– Aks
Mar 22 at 8:47





This will require using Set which is still under development. More info here:- github.com/realm/realm-java/issues/759 For now you have manually check before adding new items that your list don't contain the item you are trying to add.

– Aks
Mar 22 at 8:47












1 Answer
1






active

oldest

votes


















0














You can just use Set to get rid of the duplicates before adding your objects to a List. Just make sure you make your types conform to Hashable that you want to add to a Set.



Some general advice: you don't need to create CodingKeys when the property names match the JSON keys unless you create a custom init(from decoder:) method and you don't need to create a custom init(from:) method unless you do some custom stuff, like use decodeIfPresent and filter duplicate objects. For Playlists and Tracks, you can rely on the synthetised initializer.



You also don't need to add elements from an array to a List in a loop, just use append(objectsIn:), which accepts a Sequence as its input argument.



class Songs: Object, Decodable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()

enum CodingKeys: String, CodingKey
case playlists, tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
let uniquePlaylists = Set(playLists)
self.playlists.append(objectsIn: uniquePlaylists)


if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
let uniqueTrackList = Set(tracksList)
self.tracks.append(objectsIn: uniqueTrackList)




class Playlists: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0

override static func primaryKey() -> String?
return "id"




class Tracks: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0

override static func primaryKey() -> String?
return "id"




If you want to make sure you don't add any objects twice to Realm, you need to use add(_:,update:) instead of add and use the primaryKey to avoid adding elements with the same keys.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData, update: true)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")






share|improve this answer

























  • Thank you @David It really help me but now I stuck on one point, what if I get same response from server multiple times or I made server call multiple times then the tracks and playlist get duplicated. how I can solve that with primary key into the given relationship. Or I can delete the table with relationship

    – Chetan
    Mar 22 at 14:30












Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55293902%2favoid-duplication-in-array-of-custom-object-in-realm-database-when-primary-key%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









0














You can just use Set to get rid of the duplicates before adding your objects to a List. Just make sure you make your types conform to Hashable that you want to add to a Set.



Some general advice: you don't need to create CodingKeys when the property names match the JSON keys unless you create a custom init(from decoder:) method and you don't need to create a custom init(from:) method unless you do some custom stuff, like use decodeIfPresent and filter duplicate objects. For Playlists and Tracks, you can rely on the synthetised initializer.



You also don't need to add elements from an array to a List in a loop, just use append(objectsIn:), which accepts a Sequence as its input argument.



class Songs: Object, Decodable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()

enum CodingKeys: String, CodingKey
case playlists, tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
let uniquePlaylists = Set(playLists)
self.playlists.append(objectsIn: uniquePlaylists)


if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
let uniqueTrackList = Set(tracksList)
self.tracks.append(objectsIn: uniqueTrackList)




class Playlists: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0

override static func primaryKey() -> String?
return "id"




class Tracks: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0

override static func primaryKey() -> String?
return "id"




If you want to make sure you don't add any objects twice to Realm, you need to use add(_:,update:) instead of add and use the primaryKey to avoid adding elements with the same keys.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData, update: true)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")






share|improve this answer

























  • Thank you @David It really help me but now I stuck on one point, what if I get same response from server multiple times or I made server call multiple times then the tracks and playlist get duplicated. how I can solve that with primary key into the given relationship. Or I can delete the table with relationship

    – Chetan
    Mar 22 at 14:30
















0














You can just use Set to get rid of the duplicates before adding your objects to a List. Just make sure you make your types conform to Hashable that you want to add to a Set.



Some general advice: you don't need to create CodingKeys when the property names match the JSON keys unless you create a custom init(from decoder:) method and you don't need to create a custom init(from:) method unless you do some custom stuff, like use decodeIfPresent and filter duplicate objects. For Playlists and Tracks, you can rely on the synthetised initializer.



You also don't need to add elements from an array to a List in a loop, just use append(objectsIn:), which accepts a Sequence as its input argument.



class Songs: Object, Decodable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()

enum CodingKeys: String, CodingKey
case playlists, tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
let uniquePlaylists = Set(playLists)
self.playlists.append(objectsIn: uniquePlaylists)


if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
let uniqueTrackList = Set(tracksList)
self.tracks.append(objectsIn: uniqueTrackList)




class Playlists: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0

override static func primaryKey() -> String?
return "id"




class Tracks: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0

override static func primaryKey() -> String?
return "id"




If you want to make sure you don't add any objects twice to Realm, you need to use add(_:,update:) instead of add and use the primaryKey to avoid adding elements with the same keys.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData, update: true)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")






share|improve this answer

























  • Thank you @David It really help me but now I stuck on one point, what if I get same response from server multiple times or I made server call multiple times then the tracks and playlist get duplicated. how I can solve that with primary key into the given relationship. Or I can delete the table with relationship

    – Chetan
    Mar 22 at 14:30














0












0








0







You can just use Set to get rid of the duplicates before adding your objects to a List. Just make sure you make your types conform to Hashable that you want to add to a Set.



Some general advice: you don't need to create CodingKeys when the property names match the JSON keys unless you create a custom init(from decoder:) method and you don't need to create a custom init(from:) method unless you do some custom stuff, like use decodeIfPresent and filter duplicate objects. For Playlists and Tracks, you can rely on the synthetised initializer.



You also don't need to add elements from an array to a List in a loop, just use append(objectsIn:), which accepts a Sequence as its input argument.



class Songs: Object, Decodable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()

enum CodingKeys: String, CodingKey
case playlists, tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
let uniquePlaylists = Set(playLists)
self.playlists.append(objectsIn: uniquePlaylists)


if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
let uniqueTrackList = Set(tracksList)
self.tracks.append(objectsIn: uniqueTrackList)




class Playlists: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0

override static func primaryKey() -> String?
return "id"




class Tracks: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0

override static func primaryKey() -> String?
return "id"




If you want to make sure you don't add any objects twice to Realm, you need to use add(_:,update:) instead of add and use the primaryKey to avoid adding elements with the same keys.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData, update: true)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")






share|improve this answer















You can just use Set to get rid of the duplicates before adding your objects to a List. Just make sure you make your types conform to Hashable that you want to add to a Set.



Some general advice: you don't need to create CodingKeys when the property names match the JSON keys unless you create a custom init(from decoder:) method and you don't need to create a custom init(from:) method unless you do some custom stuff, like use decodeIfPresent and filter duplicate objects. For Playlists and Tracks, you can rely on the synthetised initializer.



You also don't need to add elements from an array to a List in a loop, just use append(objectsIn:), which accepts a Sequence as its input argument.



class Songs: Object, Decodable 
let playlists = List<Playlists>()
let tracks = List<Tracks>()

enum CodingKeys: String, CodingKey
case playlists, tracks


required convenience public init(from decoder: Decoder) throws
self.init()
let container = try decoder.container(keyedBy: CodingKeys.self)
if let playLists = try container.decodeIfPresent([Playlists].self, forKey: .playlists)
let uniquePlaylists = Set(playLists)
self.playlists.append(objectsIn: uniquePlaylists)


if let tracksList = try container.decodeIfPresent([Tracks].self, forKey: .tracks)
let uniqueTrackList = Set(tracksList)
self.tracks.append(objectsIn: uniqueTrackList)




class Playlists: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var duration: Int = 0

override static func primaryKey() -> String?
return "id"




class Tracks: Object, Codable, Hashable
@objc dynamic var id: String = ""
@objc dynamic var name: String = ""
@objc dynamic var artist: Int = 0

override static func primaryKey() -> String?
return "id"




If you want to make sure you don't add any objects twice to Realm, you need to use add(_:,update:) instead of add and use the primaryKey to avoid adding elements with the same keys.



SongsData = try jsonDecoder.decode(Songs.self, from: data)
let realm = try! Realm()
try! realm.write
realm.add(SongsData, update: true)
catch
Logger.log.printOnConsole(string: "Unable to convert to data")







share|improve this answer














share|improve this answer



share|improve this answer








edited Mar 22 at 14:35

























answered Mar 22 at 9:59









Dávid PásztorDávid Pásztor

23.3k83152




23.3k83152












  • Thank you @David It really help me but now I stuck on one point, what if I get same response from server multiple times or I made server call multiple times then the tracks and playlist get duplicated. how I can solve that with primary key into the given relationship. Or I can delete the table with relationship

    – Chetan
    Mar 22 at 14:30


















  • Thank you @David It really help me but now I stuck on one point, what if I get same response from server multiple times or I made server call multiple times then the tracks and playlist get duplicated. how I can solve that with primary key into the given relationship. Or I can delete the table with relationship

    – Chetan
    Mar 22 at 14:30

















Thank you @David It really help me but now I stuck on one point, what if I get same response from server multiple times or I made server call multiple times then the tracks and playlist get duplicated. how I can solve that with primary key into the given relationship. Or I can delete the table with relationship

– Chetan
Mar 22 at 14:30






Thank you @David It really help me but now I stuck on one point, what if I get same response from server multiple times or I made server call multiple times then the tracks and playlist get duplicated. how I can solve that with primary key into the given relationship. Or I can delete the table with relationship

– Chetan
Mar 22 at 14:30




















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55293902%2favoid-duplication-in-array-of-custom-object-in-realm-database-when-primary-key%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현