3
votes

I am working on iOS and that is saving product. and this product has some more things inside its model

let suppose the following model

@objcMembers public class ProductModel : Object, Codable {

  dynamic var Id : Int = 0
  dynamic var Name : String = 0
  dynamic var Price : Double = 0.0

}

and the other model (CustomerModel) that contains the ProductModel is as follow

 @objcMembers public class CustomerModel : Object, Codable {

  dynamic var Id : Int = 0
  dynamic var Name : String = 0
  var Product : ProductModel? = nil 

}

Now when I save customer with the product inside it, I can see that in Realm it gets saved successfully. But if and only if that object is not in Realm already,

Let suppose this

let customer1 = CustomerModel()
customer1.Id = ...
customer1.Name =  .....
customer1.Product = product1 

Now this customer data is saved. But I am getting exception if I try to save following data

let customer2 = CustomerModel()
    customer2.Id = ...
    customer2.Name =  .....
    customer2.Product = product1

Just notice that customer2 also want to save product info that is already saved in Realm namely "product1".

So how to handle this sitution.

I am trying to save the data with the following generic function for realm objects

func save <T: Object> (_ obj : T){
do {
    try realmObj.write{
        realm.add(obj)
    }
  }catch{}

}

Question 2:

Also I want to get All Customer, I know how to do it, but problem is It never retrieves the Product inside the Customer. I can see in Realm DB Browser that the customer that get saved with the product, that customer table contains the reference of Product also. But when I try to get all customer then that customer have only customer details not Product detail. Whereas that must be there.

1
Have you tried add(_:update:) method, with update = true? - Nishu_Priya
Also CustomerModel or product model does not have any primary key. Try adding those as well. - Nishu_Priya
yes those have primary key, those models are just demo - A.s.ALI
okay, and did add(_:update:) method work? I used to do what you are doing and I was not doing anything different. Can you post the exact error? - Nishu_Priya
yes just after I posted question, I tried update and it did work. But How about retrieving data from Realm. See my updated answer. - A.s.ALI

1 Answers

4
votes

Just put dynamic keyword before your property

dynamic var Product : ProductModel? = nil