Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a non realm object as ignored property to realm object in swift?

Tags:

ios

swift

realm

I am trying to add a non-realm class object to realm object something like this.

class TrainTripItinerary: Object {
    dynamic var  departStationName: String?
    dynamic var  departStationCode: String?
    var runningStatus: TrainRunningStatus?

    override static func ignoredProperties() -> [String] {
        return ["runningStatus"]
    }

}

While TrainRunningStatus is not a realm class.

class TrainRunningStatus {
    var trainDataFound: String?
    var startDate: String?
    var startDayDiff: String?
}

I am not able to update runningstatus property now. Anyone know how it works? I fetch separately runnningstatus and assign it to the realm object later but it stays nil even after the assignment.

eg.

let runningStatus = TrainRunningStatus()
trainTripItinerary.runningStatus = runningStatus

This line is not working, trainTripItinerary runningStatus property is not set properly its always nil.

like image 941
kidsid49 Avatar asked Mar 08 '17 12:03

kidsid49


2 Answers

As suggested in comments make sure you use the same instance of TrainTripItinerary because ignored properties won’t automatically update their value across different instances.

See an example code below that demonstrates how ignored properties work

let realm = try! Realm()

try! realm.write {
    realm.deleteAll()
}

let runningStatus = TrainRunningStatus()

var trainTripItinerary = TrainTripItinerary()
trainTripItinerary.runningStatus = runningStatus

assert(trainTripItinerary.runningStatus != nil)

try! realm.write {
    realm.add(trainTripItinerary);
}

assert(trainTripItinerary.runningStatus != nil)

trainTripItinerary = realm.objects(TrainTripItinerary.self).first!

assert(trainTripItinerary.runningStatus == nil)
like image 165
Dmitry Avatar answered Oct 15 '22 14:10

Dmitry


Firstly, your code is not correct.

class TrainTripItinerary: Object {
    dynamic var  departStationName: String?
    dynamic var  departStationCode: String?
    var runningStatus: TrainRunningStatus?

    override static func ignoredProperties() -> [String] {
        return ["runningStatus"]
    }
}

func ignoredProperties() -> [String] is only used on Realm properties. Since your property var runningStatus: TrainRunningStatus? does not begin with dynamic, it is not a Realm property. You don't need to use func ignoredProperties() -> [String] here.

var runningStatus: TrainRunningStatus? here is called a "transient property" in Realm. Usually a transient property is something calculated basing on current date or on Realm properties, Realm won't do anything on transient properties and you should maintain them yourself.

So if you just want to use runningStatus as a transient property, you can simply remove the code override static func ignoredProperties() -> [String].

like image 42
Owen Zhao Avatar answered Oct 15 '22 13:10

Owen Zhao