试图创建一个Swift领域数据模型

时间:2014-12-22 04:05:45

标签: ios swift realm

我查看了Realm.io文档。我正在开发一个跟踪我的车辆费用的应用程序。我已经把我认为可能对Realm中的数据模型起作用的东西放在一起,但我是新手,并且不确定这是否会起作用或者是否有更好的方法。这就是我所拥有的,我没有把它放在一个项目中并尝试编译。 realm.io docs对我来说有点模糊,所以也许有人可以告诉我你的想法。我在一些地方加入了一些评论,我不知道如何实现我的目标......

    // Vehicle model
class Vehicle : RLMObject {
    dynamic var name = “”
    dynamic var number = “”
    dynamic var currentMiles = 0
    dynamic var entries = RLMArray(objectClassName: Entry.className())
}

// Entry model
class Entry: RLMObject {
    dynamic var vehicle: Vehicle //??
    dynamic var date = NSDate()
    dynamic var expense = 0.0
    dynamic var mileage : Vehicle.currentMiles // want to update the Vehicle mileage with each entry

}

// Gas model
class Gas: Entry {
    dynamic var gallons = 0
    dynamic var pricePerGallon = 0.0
}

// OilChange model
class OilChange : Entry {
    dynamic var milesBetweenChanges = 0
}

// Other Service model
class OtherService: Entry {
    dynamic var notes = “”
}

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上!我认为唯一需要工作的模型是Entry。首先,使用我的注释找到你的模型:

// Entry model
class Entry: RLMObject {
    dynamic var vehicle: Vehicle // This is valid Swift, but you'll need to set the value in the designated initializer (`init()`).
    dynamic var date = NSDate()
    dynamic var expense = 0.0
    dynamic var mileage : Vehicle.currentMiles // This isn't valid Swift, since `Vehicle` is a class, and doesn't have a `currentMiles` member
}

你想要的是这样的:

// Entry model
class Entry: RLMObject {
    dynamic var vehicle = Vehicle() // Use a default value so that `init()` succeeds, but you can still use `init(vehicle: Vehicle)` in your code
    dynamic var date = NSDate()
    dynamic var expense = 0.0
    dynamic var mileage = 0

    init() {
        // Must override init() when adding a convenience initializer
        super.init()
    }

    convenience init(vehicle: Vehicle) {
        super.init()
        self.vehicle = vehicle
        mileage = vehicle.currentMiles
    }
}

很遗憾,你发现Realm的文档模糊不清。如果您有任何特别想要我们澄清的信息,请告诉我们。我们是一群非常平易近人的人!