Two Table Views, Two Models - ios

Is it possible to have one data model that populates 2 or more tableviews? I am using 2 models at the moment and have been having some trouble:
class Soccer: Object {
dynamic var player = ""
dynamic var highscore = ""
dynamic var talents = ""
}
class Cricket: Object {
dynamic var player = ""
dynamic var highscore = ""
dynamic var talents = ""
}
1 tableview is supposed to get data from the Soccer model, the 2nd tableview from the Cricket model. I am using Realm.isEmpty to check if I have a Realm when the app launches, located in my AppDelegate:
class SetUpData {
static func defaults() {
let realm = try! Realm()
guard realm.isEmpty else { return }
try! realm.write {
realm.add(Article.self())
}
}
}
This pre-populates my SoccerTableViewController UI. But I cannot achieve the same result with CricketTableViewController. I am doing everything in code and am trying to learn the best way to go about populating multiple tableviews using Realm Swift.

Did you mean like this?
class Sport: Object {
dynamic var player = ""
dynamic var highscore = ""
dynamic var talents = ""
}
class Soccer: Sport {
// ...
}
class Cricket: Sport {
// ...
}
class SportTableViewController: UIViewController {
var tableViewDatas: [Sport]?
// ...
}
class SoccerTableViewController: SportTableViewController {
// ...
}
class CricketTableViewController: SportTableViewController {
// ...
}

Related

how to avoid adding the same data in Realm database in many to many relationship?

I have wishlistVC that has collection view like the picture below:
I have product realm model like this:
class Product : Object {
#objc dynamic var productID : String = ""
#objc dynamic var name : String = ""
#objc dynamic var unitPrice: Double = 0.0
#objc dynamic var quantity = 0
#objc dynamic var descriptionProduct : String = ""
#objc dynamic var hasBeenAddedToWishList : Bool = false
#objc dynamic var hasBeenAddedToCart : Bool = false
#objc dynamic var isNewProduct : Bool = false
var imagePaths = List<String>()
}
and WishList realm model like this:
class WishList : Object {
#objc dynamic var userID: String = ""
var products = List<Product>() // many to many relationship
static func getWishListFromRealmDatabase() -> WishList {
let userID = "1"
let allWishList = RealmService.shared.realm.objects(WishList.self)
let theWishList = allWishList.filter("userID CONTAINS[cd] %#", userID).first
if let userWishList = theWishList {
return userWishList
} else {
// WishList never setted up before in Realm database container
// then create WishList in realm database
let newWishList = WishList()
newWishList.userID = userID
newWishList.products = List<Product>()
RealmService.shared.save(object: newWishList)
return newWishList
}
}
static func addProductToWishListRealmDatabase(userWishList: WishList, selectedProduct: Product) {
// to check wheter the selected product from user is already in WishList or not
if userWishList.products.filter("productID == %#", selectedProduct.productID).first == nil {
RealmService.shared.save(expression: {
selectedProduct.hasBeenAddedToWishList = true
userWishList.products.append(selectedProduct)
})
}
}
}
when the user tap that love button, here is the code used to add product to WishList:
func addProductToWishListRealmDatabase(userWishList: WishList, selectedProduct: Product) {
// to check wheter the selected product from user is already in WishList.products or not
if userWishList.products.filter("productID == %#", selectedProduct.productID).first == nil {
// write in realm database
RealmService.shared.save(expression: { // <-- this is just a wrapper to avoid write do try catch block all over the place
selectedProduct.hasBeenAddedToWishList = true
userWishList.products.append(selectedProduct)
})
}
}
and here is the full simplified code of my WishListVC:
class WishListVC : UIViewController {
#IBOutlet weak var wishListCollectionView: UICollectionView!
private var userWishList : WishList?
private var products = List<Product>()
private var selectedProduct : Product?
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
userWishList = WishList.getWishListFromRealmDatabase() // the definition is in the code above
guard let userWishList = userWishList else {return}
products = userWishList.products
}
}
extension WishListVC : ListProductCellDelegate {
func likeButtonDidTapped(at selectedIndexPath: IndexPath, productHasBeenLiked: Bool, collectionView: UICollectionView) {
guard let userWishList = userWishList else {return}
let selectedProduct = products[selectedIndexPath.item]
if productHasBeenLiked {
WishList.removeProductFromWishListRealmDatabase(userWishList: userWishList, selectedProduct: selectedProduct)
} else {
WishList.addProductToWishListRealmDatabase(userWishList: userWishList, selectedProduct: selectedProduct)
}
wishListCollectionView.reloadData()
self.wishListCollectionView.isHidden = userWishList.products.isEmpty
}
}
if I append a product to the wishlist model like the code above, it will affect to the Product.self in realm database, it will keep adding the product in 'Product Realm Database', as you can see in the image below, there are 9 data in Product, but as you can see some of the product have the same productID, there are 3 products that have 'a' as the productID .
so how to avoid adding the product that has the same productID in 'Product Realm Database' (Product.self) when I modify the WishList by appending the product to wishlist.products ?
I have also tried to add primary key using:
override static func primaryKey() -> String? {
return "productID"
}
but It makes crash with message:
*** Terminating app due to uncaught exception 'RLMException', reason: 'Attempting to create an object of type 'Product' with an existing
primary key value 'a'.'
it will throw error because I add productID = 'a'
what should I do ? how to append product to the WishList model but I also can avoid adding the same product that has the same productID to the Product Realm database model (Product.self) ?
do I use the wrong approach to add the product to the wishlist?

How to make search query to get all Objects in Realm

I am creating a Realm object like below
import RealmSwift
class Item: Object {
#objc dynamic var ID = 0
#objc dynamic var notificationTitleString = ""
#objc dynamic var notificationBodyString = ""
#objc dynamic var notificationDateString = ""
#objc dynamic var notificationType = ""
#objc dynamic var notificationUrl = ""
#objc dynamic var notificationActivity = ""
#objc dynamic var notificationIsRead = ""
override static func primaryKey() -> String? {
return "ID"
}
}
I am using the below method to get a particular item type
import UIKit
import RealmSwift
class DBManager {
private var database: Realm
static let sharedInstance = DBManager()
private init() {
database = try! Realm()
print(Realm.Configuration.defaultConfiguration.fileURL!)
}
func fetchNotificationType(type: String) -> Results<Item> {
let predicate = NSPredicate(format: "notificationType = %#", type)
let results : Results = database.objects(Item.self).filter(predicate)
return results
}
}
Using the above fetchNotificationType method i am able to get a single object, But i want all the objects in a single query. I do not know how to do that, I am trying Realm for the first time.
I searched SO, but i did not get any related answers.

Adding a new relationship to an existing model in Realm

I'm developing an iOS application using Realm and have a object MedicationObject which contains the information about the Medication being used. This then has a many to one relationship class MedicationRecording which stores the information when the time the medication was taken.
import Foundation
import RealmSwift
class MedicationObject : Object {
//This model requires a Primary Key
#objc dynamic var id = 0
override static func primaryKey() -> String? {
return "id"
}
#objc dynamic var medicationName : String = ""
//stores the refrences to medication recoridngs
var messurements = List<MedicationRecording>()
public func addNewMesurment() {
print(self)
let medicationRecording = MedicationRecording()
medicationRecording.medicationTaken = self
medicationRecording.timeTaken = Date()// this saves the time to now
medicationRecording.medicationTaken = self
RealmAccess().updateMedicationObject(medicationObject: self, medicationRecord: medicationRecording) //this should work
}
}
here is my MedicationRecording:
import Foundation
import RealmSwift
class MedicationRecording : Object {
#objc dynamic var medicationTaken : MedicationObject? = MedicationObject()
#objc dynamic var timeTaken : Date = Date()
#objc dynamic var id = 0
override static func primaryKey() -> String? {
return "id"
}
}
and this is the method I'm calling to save the data to
func updateMedicationObject(medicationObject : MedicationObject, medicationRecord : MedicationRecording) {
let realm = try! getRealmAccess()
let mediObject = MedicationObject()
mediObject.medicationName = medicationObject.medicationName
do {
try! realm.write {
realm.add(medicationRecord, update: true)
medicationObject.messurements.append(medicationRecord)
}
}
}
At the moment when I'm saving the data it is then losing all the information in MedicationObject and only saving the last data.
Any help with be greatly appreciated
Thank you

How to check what class belongs AnyObject?

For example, there are two models Realm Information
import Foundation
import RealmSwift
class Music: Object {
dynamic var id = ""
dynamic var title = ""
dynamic var url = ""
}
class DownloadMusic: Object {
dynamic var id = ""
dynamic var title = ""
dynamic var path = ""
}
And there is a certain function
func test(object: AnyObject) {
}
When a call is transferred as an argument 'realm.objects(Music)[0]'
let realm = try! Realm()
test(realm.objects(Music)[0])
Can I check in function, the object belongs to a class 'Music' or to a 'DownloadMusic'
Try this:
func test(object: AnyObject) {
if object is Music {
print("music")
} else if object is DownloadMusic {
print("downloadmusic")
}
}

Singleton class for sharing data

I'm an android app developer and a beginner in swift. I'm trying to implement a singleton class whose data members are shared throughout the app (like Settings).
Getting this done in android is pretty simple but I'm breaking my head to do it in swift.
Below is the code I've tried ..
public class DataSet
{
public var notificationOnOff: Bool!
public var interval: Int!
public var alert: String!
init()
{
self.notificationOnOff = true
self.interval = 1;
self.alert = nil;
}
init (onOff: Bool) {
self.notificationOnOff = onOff
}
init (time: Int) {
self.interval = time
}
init (stop: String) {
self.alert = stop
}
}
This class implementation couldn't persist the data.
Is this the right way of doing it?
EDIT
For example, when I click switch in Settings view controller, I'm setting notificationOnOff like ..
dataset.notificationOnOff = DataSet(onOff: true) // value is set and able to print it
and using this value in another class like...
if dataset.notificationOnOff
{
// do some stuff
}
So basically, the value is persisting only within the Setting class but not when I switch to other class.
Solved!
I have used the below code to successfully implement this..
var instance: DataSet?
class Dataset {
...
class var sharedInstance: DataSet {
struct Static {
static var instance: DataSet?
static var token: dispatch_once_t = 0
}
dispatch_once(&Static.token) {
Static.instance = DataSet()
}
return Static.instance!
}
}
and in the other classes ..
dataset = Dataset.sharedInstance;

Resources