Call view controller method from custom class

I have a custom class and a view controller.

My custom class:

class ChatManager:NSObject {

    func messageArrived() {
         //When Message arrives I am handling it from here
         //I need something like that: Viewcontroller.updateTable()
    }
}

When message arrives from internet I need to update tableview in view controller. So I mean I have to call a view controller method from messageArrived method. How can I do this ?

Answers


Here is a simple example of using delegate:

declare the delegate before your chat manager class

protocol ChatManagerDelegate {
    func manageMessage()
}

when the message arrived, call the delegate method to handle it.

class ChatManager: NSObject {

    var delegate: ChatManagerDelegate?

    func messageArrived() {
        self.delegate!.manageMessage()
    }
}

in your view controller, remember to set the delegate of the chat manager to self.

class ViewController: ChatManagerDelegate {
    var manager = ChatManager()
    manager.delegate = self

    func manageMessage() {
        self.updateTable()
    }
}

This would be a possible implementation:

ViewController:

class ViewController: UIViewController,ChatManagerDelegate {

  override func viewDidLoad() {
    super.viewDidLoad()
    let myChatManager = ChatManager()
      myChatManager.delegate = self
  }


  func messageDidArrive() {
    // Do Things here.
  }
}

Chatmanager:

class ChatManager:NSObject {
  var delegate:ChatManagerDelegate?

  func messageArrived() {
    //When Message arrives I am handling it from here
    //I need something like that: Viewcontroller.updateTable()
  }
}

Delegate-Protocol:

protocol ChatManagerDelegate{
  func messageDidArrive()
}

Need Your Help

How to handle inheritance?

java json jackson couchdb ektorp

I'm using the Ektorp framework as Java "ORM" for CouchDB. It's using Jackson for (de)serialization of the JSON documents.

what's the best image input type for tesseract?

image-processing ocr tesseract

i'm using tesseract on a project and want to know the best image input type for tesseract to give the best output, is Binary&TIFF is the best input or there's something else?