Set relationship between Model classes - ios

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"

Related

Realm how to save item if not exist else it should update

I have a data coming from webservice. I have same models made in my project. To demonstrate the model let me show a little idea of my model
Model1:
class Standard {
var Id = 0
var standardName = ""
var students : [StudentModel] = nil
}
Model2:
class StudentModel {
var Id = 0
var stdName = ""
var Teacher: [TeacherModel] = nil
}
Model3:
class TeacherModel {
var Id = 0
var Name = ""
}
Now what I am facing is as follow :
I have TeacherModel in DB already, but I dont have student model and standard model instance int he Realm, so it is supposed to save coming student and standard data in Realm. and skip or update TeacherModel in Realm. But right now it is crashing on TeachModel data as one Teacher with same things are already saved in Realm.SO i am looking forward to some sort of method in which it update or just skip saving Item if already exist in the Realm.
Note: These models are just to demonstrate my case, where as I know there are many typos and other thing. Also I did not showed any implementation of Realm over my Models. Its just to show you the things to make you understand.
Well you need to have class func primaryKey() -> String? overriden.
override class func primaryKey() -> String? {
return "Id"
}
And then use realm.write(...) or realm.create(...) functions with update parameter set to true.

Realm list property not saving data

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>()
}

Can I use single NSObject class for multiple ViewController class to get data from API

I am try to use single NSObject class in which I am defined all variable those data access from server. I have multiple ViewController class those have different types of variable and string. I want to use single NSObject class to get data from server.
Is it possible?
For ViewControllerA string objects-
var id = Int()
var contactowner = String()
var status : String?
var image:String?
var title : String?
For ViewControllerB string objects-
var strImageRequesterName : String?
var strRequesterName : String?
var strRequesterPosition : String?
var strRequesterAddress : String?
of course you can , there are so much methord to do that , but i think this is a classic ‘Observer design Pattern’ Observer Design Pattern
I suggest you, Use object Mapper with alamofire for request fire and getting data in the form of objects and use callback function to get data from api, from service class.

How to link two Realm objects

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

Modal creating class object and setting values

Hello this problem is more concerned with the programming problem rather then the specific language syntax. I am getting a nil user_id value after setting a value in class object. So I thing I am doing something wrong here
I have two classes. User and Trip
Trip.swift
class Trip: NSObject {
var tripID: Int?
var tripTitle: String?
var user:User?
var params: [String:NSObject] {
return [
"user_id": self.user!.userID!,
"trip_title": self.tripTitle!,
]
}
When I send these params to server I get a nil value user_id
var trip: Trip?
trip?.user?.userID = 9
I am not writing a whole code. I think I am doing something wrong in modal class or not setting the userID correctly. Please let me know if you can't figure out the problem from this info so I'll post full code here
class User: NSObject {
var userID: Int?
var email: String?
var password: String?
var firstName: String?
var lastName: String?
var params: [String:NSObject] {
return [
"email": self.email!,
"password": self.password!,
"first_name": self.firstName!,
"last_name": self.lastName!,
]
}
If all the data in both classes is always mandatory in real life, then
you should not designate those properties as optional.
This will force you to write proper initialisers and then
you will be forced to populate each object with correct values, which in turn
will lead to abandoning the need for force-unwrapping just before you send to server.
Following these steps will fix your problem.
Bonus advice: You don't have to inherit from NSObject. Do not inherit from anything. Everything here is possible to do with swift standard library. The dictionary then will use AnyObject as value.

Resources