cyclingIsBetter
cyclingIsBetter

Reputation: 17591

iOS: Realm, check if the object is nil

I have this code where I populate an array:

func loadObjectsFromRealm() {
    private var myObjects: [MyObjects] = []
    guard let realm = try? Realm() else { return }
    myObjects = realmUtility.getAll(realm)
}

how can I check if the object is nil or not when I am going to use them? For example:

func getFirst() {
var myFirstObj = myObjects[0]    
}

Is there something to check if the object myFirstObject is real or not?

Upvotes: 1

Views: 11205

Answers (5)

Joey Slomowitz
Joey Slomowitz

Reputation: 189

I wanted to comment on the answer by @andromedainiative, but I don't have enough rep points.

'id' can't be a String - needs to be an Int;

func objectExists(id: Int) -> Bool {
        return realm.object(ofType: MyObject.self, forPrimaryKey: id) != nil
    }

//Returns true of false

objectExists(1)

Upvotes: 1

andromedainiative
andromedainiative

Reputation: 4962

// Check for specific object with primary key

func objectExist (id: String) -> Bool {
        return realm.object(ofType: MyObject.self, forPrimaryKey: id) != nil
}

// Returns true or false
objectExist(id: "1")

Upvotes: 3

larva
larva

Reputation: 5148

you may check object is really exist before access it

if var myObj: MyObjects = myObjects.indices.contains(index) ? myObjects[index] : nil {
    // myObj is exist
}

Upvotes: 0

Janmenjaya
Janmenjaya

Reputation: 4163

I tried it following way, you can check like this. Here I have just created a nil object and checked, you can do the same for your object

 let obj :UserProfile? = nil;

    if (obj == nil){
        print("nil objUser");
    }else{
        print("objUser = \(objUser)")
    }

output : nil objUser

Upvotes: 0

Orlando
Orlando

Reputation: 1529

You can try an usual Swift if statement:

if let myFirstObj = myObjects.first
   // Do anything with the first object
} else {
   print("No first object!")
}

I think that's enough for this case.

Upvotes: 1

Related Questions