I'm new to iOS development and currently using Realm as database. My first tableview display Restaurant object and second table display customer objects. How can i link this two objects?. Means when i click each restaurant it will display different customer.
class Restaurant: Object {
dynamic var restname: String = ""
dynamic var date: String = ""
}
class Customer: Object {
dynamic var id = 0
dynamic var name: String = ""
dynamic var price: Float = 0.0
dynamic var drinks: Float = 0.0
override static func primaryKey() -> String? {
return "id"
}
}
You make references to your models like so
class Customer: Object {
dynamic var restaurant: Restaurant?
}
You also have the possibility to get reverse relationship with LinkingObjects(fromType:, property:)
You can write in your other model
class Restaurant: Object {
let customers = LinkingObjects(fromType: Customer.self, property: "restaurant")
}
That way you don't duplicate relationships.
If I understand, in Restaurant class put this:
dynamic var _customer = Optional(Customer())
or in Customer class put this line:
dynamic var _restaurant = Optional(Restaurant())
NOTE: Name of variable with lower dash, may be any name, my habit is to put lower dash
Related
I have two models, lets call them Schools, and Teachers. Models are as under
#objcMembers public class Schools : Object {
dynamic var Id : String = ""
dynamic var UserId : Int64 = 0
dynamic var Name : String? = ""
dynamic var listTeachers : List<Teachers>? = nil
dynamic var teachersList : [Teachers]? = []
}
#objcMembers public class Teachers : Object {
dynamic var Id : String = ""
dynamic var UserId : Int64 = 0
dynamic var Name : String? = ""
}
now before saving data I m putting Teachers objects (list) in School object then I save that School object in realm write closure.
after that I just get the School realm object and when I get the Teachers list, it always gets Nil. What is the case?
Am i missing something or missing something to understand the real LIST property??
please help
Update: This is how I am getting object
let mSavedItems = mDbHelper.realmObj.objects(Schools.self)
if let teachers = mSavedItems[0].teachersList{// here teacher list is nil
}
Your Schools declaration is flawed. You shouldn't declare a List as dynamic or mutable, nor should you make it Optional. As the docs clearly state, let listTeachers = List<Teachers>() is the correct way to declare a many-to-many relationship.
Storing a property of type Array is also not supported by Realm, so you should delete the teachersList : [Teachers]? property.
#objcMembers public class Schools : Object {
dynamic var Id : String = ""
dynamic var UserId : Int64 = 0
dynamic var Name : String? = ""
let listTeachers = List<Teachers>()
}
My class
class ScoreModel {
var playerId: Int?
var holeScores: [HoleScore]?
}
Other Class
class HoleScore {
var holeScore: Int?
}
I have these classes one is ScoreModel class which can have Array of objects of HoleScore
let scoreList = [ScoreModel]()
scoreList[0].holeScores![0].holeScore = 3
When i update or change holeScore for scoreList[0].holeScores[0] it changes it for all the scoreList[forAllIndexes].holeScores[0]. I just want to change the inner array prams for given index of outer array but it changes all the holeScore values when ever update.
This appends the same object , so change in one reflects to others
var item = HoleScore()
for i in 0...5
{
item. holeScore = i
scoreList[0].holeScores.append(item)
}
//
This appends different objects , so change in one doesn't reflects to others
for i in 0...5
{
var item = HoleScore()
item. holeScore = i
scoreList[0].holeScores.append(item)
}
Just solved my problem converting my classes to struct .I just did not know how to deal with this reference types in a nested sub arrays .So I used struct
struct ScoreModel {
var playerId: Int?
var holeScores: [HoleScore]?
}
struct HoleScore {
var holeScore: Int?
}
Now setting value for a specific inner index will not effect others
let scoreList = [ScoreModel]()
scoreList[0].holeScores![0].holeScore = 3
Hello I need to know what would be the standard way to implement this kind a functionality.I'll explain first the whole scenario
I have two Model classes User and Trips
class User: NSObject {
var email: String?
var password: String?
var firstName: String?
var lastName: String?
}
class Trip: NSObject {
var tripTitle: String?
var tripSummary: String?
var departureCountry: String?
var destinationCountry: String?
}
Now in the database I use join query in trips and User table when I fetch results in Trips Controller because I have to get the user information as well like his name
My Program is like this I get each variables from the backend and set them in trip Class object and then pass this object through segue. Now the problem here comes when I have to set the userinformation as well which I get in the same array. I know I have to create user object if I have to set these variables as well but how can I pass two objects through segue or should I have to to do some changing in the trips Model Class?
Is there any standard or proper way to handle this kind a situation ?
You can declare the object of User class inside the Trip class.
class Trip : NSObject
{
var userInfo : User?
var tripTitle : String?
var tripSummary : String?
var departureCountry : String?
var destinationCountry : String?
}
Then you can set the data like:
let trip = Trip() // Initialise trip
trip.userInfo = User() // Initialise user
trip.userInfo!.firstName = "Midhun"
trip.userInfo!.lastName = "MP"
I want to use Realm to my iOS app but I have a problem with the relationship. What I want to achieve is a relationship between the following two RLMobjects :
class Catalogue: RLMObject {
dynamic var ID = ""
dynamic var greekName = ""
dynamic var deutschName = ""
dynamic var createdAt = NSDate()
dynamic var updatedAt = NSDate()
override class func primaryKey() -> String? {
return "ID"
}
}
class Products: RLMObject {
dynamic var foodName = ""
dynamic var foodDescription = ""
dynamic var foodPrice = ""
dynamic var createdAt = NSDate()
dynamic var updatedAt = NSDate()
dynamic var category: Catalogue?
}
I am retrieving all my data from a server in JSON format and the problem is that
I can not set the category as relationship to Catalogue ID.
In my database the category field is a foreign key to the Catalogue ID.
Does anyone knows how can I do that in Realm?
Thank you in advance.
Rather than storing the Catalogue ID in the dynamic var category: Catalogue? relationship field you will need to find the Catalogue object and just store that directly. This is how you link objects and is an important and powerful part of using NoSQL type DB's like Realm.
I would also add an array of products relationship on Catalogue so that you can link all the products to the Catalogue itself.
You can see more discussion about this here if that wasn't fully clear. Hope this helps
I have looked at the Realm.io docs. I am working on an application to track my vehicle expenses. I have put together what I think might work for a data model in Realm, but I am new to it and not sure if this is something that will work or if there is a better way to do it. Here is what I have, and I have not put this in a project and tried to compile yet. The realm.io docs are a little vague to me, so maybe someone can tell me what you think. I have included some comments in places that I am just not sure how to achieve what I'm going for...
// 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 = “”
}
You're on the right track! The only model that needs work is Entry, I think. First, here's your model with my annotations:
// 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
}
What you want is something like this:
// 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
}
}
It's unfortunate that you find Realm's docs vague. Please let us know if there's anything in particular you'd like us to clarify. We're a pretty approachable bunch!