Search code examples
iosuitableviewswift2uiapplicationdelegate

UIViewController Delegate of DataModel Class?


I want a UIViewController to be delegate of DataModel.

In my Data Model there is a lazy loading of data from parse when I instantiate it, which basically happens from app delegate's applicationDidBecomeActive(application: UIApplication) function, and in my data model I am fetching Parse objects by Query.findObjectsInBackgroundWithBlock({ (success, error:NSError?) function.

I want the delegates to be called in the success block. I want to know if it is possible to make a UIViewController delegate of a Data model? and if yes any example.

This is what I am doing currently -

In App Delegate -

class AppDelegate: UIResponder, UIApplicationDelegate {
let dataModel = DataModel()
func applicationDidBecomeActive(application: UIApplication) {
    dataModel.handleFirstTime()
    }
}

In Data Model Class -

protocol DataModelDelegate:class{
func dataDidLoad(controller:DataModel)
func dataHaveError(controller:DataModel)}

class DataModel {
weak var delegate:DataModelDelegate?
var dataApplied = [PFObject]()

func handleFirstTime(){
let appliedQuery = PFQuery(className: "DummyClass")
    appliedQuery.findObjectsInBackgroundWithBlock({ (success, error:NSError?) -> Void in
        if error != nil {
            print(error?.userInfo)
        }else{
            dataApplied = success!
            self.delegate?.dataDidLoad(self)
            print(dataApplied.count)
        }
    })
}
}

In my ViewController -

class tableViewController: UITableViewController,DataModelDelegate { 
 override func viewDidLoad() {
    super.viewDidLoad()
    let dataModel:DataModel = DataModel()
    dataModel.delegate = self
 }
func dataDidLoad(controller: DataModel) {
    print("TableView Reload trigger")
    tableView.reloadData()
 }
//There are other TableView Controller related methods
}

Solution

  • Well, your code looks all fine at first sight. But problem here is you are setting your view controller delegate on a different object of DataModel.

    You need to ensure that you are not creating another object of DataModel in your tableViewController and use the same object you created in your AppDelegate as that is the object you used to trigger your handleFirstTime() function.

    So, your table controller is monitoring object 2 whereas in your handleFirstTime(), delegate on object 1 is being called.

    As a side note, you can also try with a singleton DataModel if you are accessing this object from many places.