Add Only Objects That Don't Currently Exist To Realm Database
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?
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.
Related Questions
- → Function Undefined in Axios promise
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Click to navigate on mobile devices
- → Playing Video - Server is not correctly configured - 12939
- → How to allow api access to android or ios app only(laravel)?
- → Axios array map callback
- → Access the Camera and CameraRoll on Android using React Native?
- → Update React [Native] View on Day Change
- → Shopify iOS SDK - issue converting BuyProductVariant to BuyProduct
- → BigCommerce and shopify API
- → Warning: Each child in an array or iterator should have a unique "key" prop. Check the render method of `ListView`
- → React Native - Differences between Android and IOS
- → What is the difference between React Native and React?