I have 2 realm object class AlertRSM and AlertRSMList that contains attributes
class AlertRSM : Object{
var alertType : String?
var alertTypeValue : String?
var period : String?
var colorValue : String?
var tableName : String?
}
class AlertRSMList: Object {
dynamic var companyAlt_Key :String?
dynamic var dbEntryDate :String?
var arrayOfAlertRSM = List<AlertRSM>()
}
I already have data in realm DB, and fetching it like
let alertRSMList = realm.objects(AlertRSMList.self)
let selectedAlertRSMList : [AlertRSMList] = alertRSMList.filter { alertRSM in
return alertRSM.companyAlt_Key == _companyAlt_Key
}
I am getting records in selectedAlertRSMList. Now I want to get AlertRSM array form selectedAlertRSMList for that I did the below
if selectedAlertRSMList.count > 0 {
/*var alertRSM = [AlertRSM]()
let alertList = selectedAlertList[0].arrayOfAlertRSM
for item in alertList {
alertRSM.append(item)
}
// print(alertRSM.count) // here I am getting 9 count but all items are nil
*/
let alertList = selectedAlertList[0].arrayOfAlertRSM
print(alertList) // I am getting all records
print(alertList[0].alertType)// here I am getting nil but that is exist in alertList and also printed by print(alertList)
}
by printing alertList
print(alertList)
I am getting records like
List<AlertRSM> <0x6000002e0500> (
[0] AlertRSM {
alertType = Financial;
alertTypeValue = 37.0;
period = W;
colorValue = 008000;
tableName = Alert;
},
[1].....so on
but when I am trying to print
print(alertList[0].alertType)
I am getting nil printed
nil
Please suggest me help would be appreciated :-)
You need to declare all instance properties of your Realm model classes using the dynamic
keyword to be usable as stored Realm properties. This is needed for Objective-C interoperability, since the Realm framework uses the Obj-C runtime environment.
After declaring all properties as dynamic
, your code works just fine.
class AlertRSM : Object {
dynamic var alertType : String?
dynamic var alertTypeValue : String?
dynamic var period : String?
dynamic var colorValue : String?
dynamic var tableName : String?
}
The issue can clearly be seen if you run your code on instances of your classes that are not persisted in Realm. On those, your code works perfectly, since they are not accessed through the Obj-C runtime. As soon as you persist the model objects, the issue can be seen.
From the Realm docs:
Realm model properties must have the @objc dynamic var attribute to become accessors for the underlying database data.
There are three exceptions to this: LinkingObjects, List and RealmOptional. Those properties cannot be declared as dynamic because generic properties cannot be represented in the Objective‑C runtime, which is used for dynamic dispatch of dynamic properties. These properties should always be declared with let.