Reputation: 1817
So i'm trying to set up and pre populate a database for later use when the actual application ships.
The issue i'm having is i'm not able to insert into the field which is creating the relationship the field is just empty. Screenshot below:
The data model holding the info the type is the key to the other object
class sourceRecentData: Object {
// Name
dynamic var sourceName: String = ""
// Description
dynamic var sourceDesc: String = ""
// TypeID
dynamic var type : sourceType?
// Key
dynamic var sourceKey: String = ""
// Enabled
dynamic var sourceEnabled: Bool = true
// Unlocked
dynamic var sourceUnlocked: Bool = false
}
The id in this object links to the object above
class sourceType: Object {
// NewsType
dynamic var typeOfNews: String = ""
}
The method i'm using to perform the insert for now it's just dummy data
func createTopDB() {
let recentData = sourceRecentData()
let realm = try! Realm()
recentData.sourceName = "dfdfd"
recentData.sourceDesc = "fdfd"
recentData.sourceKey = "fdfdf"
recentData.sourceEnabled = true
recentData.sourceUnlocked = false
recentData.type?.typeOfNews = "fdfdfd"
try! realm.write({ () -> Void in
realm.add(recentData)
})
}
Upvotes: 2
Views: 1570
Reputation: 7806
You need to initialize your property first with a related object, before you can write values on it. I'd recommend to that in a separate variable like shown below, so you can avoid writing on an optional value (recentData.type?.typeOfNews = …
):
let type = SourceType()
type.typeOfNews = "fdfdfd"
recentData.type = type
You can query for the object like that:
let realm = try! Realm()
let objects = realm.objects(SourceRecentData).filter("type.id = 1")
PS: I'd recommend to name your classes beginning with an uppercase letter as this is a general best-practice in the Swift programming community and make it easier to differentiate between classes and variables. I applied that in the following example code to make it easier to read, because SO's syntax highlighting relies on that convention as well.
Upvotes: 5
Reputation: 129
Won't recentData.type?.typeOfNews = "fdfdfd"
be a non operation? It will be a None "value" by default.
You need to create an instance of sourceType
, set the property, and then assign that to recentData.type
.
Upvotes: 1