Ad

Add Only Objects That Don't Currently Exist To Realm Database

- 1 answer

I have a subjects Realm database:

import Foundation
import RealmSwift

class Subjects: Object {

dynamic var subject = "" 

override static func primaryKey() -> String? {
    return "subject"
  }

}

In the database I have four subjects, say, Computing 101, English, History and Geography. Now, I have a struct that can hold an array of subjects, like so:

struct mySubjects {

static var subjects:Array<String>  = [String]()

 }

The user can add subjects to the struct, say, Computing 101, English, History, Geography and Accountancy for Engineers.

My problem is that I only want to add the one subject that does not already exist in the database, i.e. "Accountancy for Engineers". I thought I could simply code a NSPredicate like so:

 for subject in mySubjects.subjects  {

    let myPredicate:NSPredicate = NSPredicate(format: "subject != '\(subject)'")
    results = realm.objects(Subjects).filter(myPredicate)

No luck :(. Any suggestions?

Ad

Answer

Because you've set up a primary key, you could use the objectForPrimaryKey(_:key:) function.

If the result of something like realm.objectForPrimaryKey(Subject.self, "Subject Name") is nil, then that subject doesn't exist in the database yet.

Ad
source: stackoverflow.com
Ad