I am using Protocol and Delegates for saving api data into delegate method and in another class, fetching it. But in second class, when i declared this property. It shows an error message.
'DepartmentDataDelegate' cannot be constructed because it has no accessible initializers
Class A : Add protocol for saving api data into the delegate method.
protocol DepartmentDataDelegate {
func showDepttData(departments: [String : Any])
}
var delegate: DepartmentDataDelegate?
Stored api data into protocol method
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: [Any]] {
//print("POST Method :\(json)")
DispatchQueue.main.async {
for eachDepartment in json["departments"]!
{
let eachData = eachDepartment as! [String: Any]
self.delegate?.showDepttData(departments: eachData)
}
self.tableView.reloadData()
}
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
Class B : This class is fetching the department data and print here.
class ShowEmpVC: UIViewController, DepartmentDataDelegate {
//Department Data Delegate
var depttDelegate = DepartmentDataDelegate()
var depttData = [String : Any]()
override func viewDidLoad() {
super.viewDidLoad()
depttDelegate = self
print("Departmens are : \(depttData)")
}
}
In your protocol not have a init()
func. So you not call DepartmentDataDelegate()
. Try this:
Class A:
protocol DepartmentDataDelegate {
func showDepttData(departments: [String : Any])
}
static var delegate: DepartmentDataDelegate?
Class B:
class ShowEmpVC: UIViewController, DepartmentDataDelegate {
var depttData = [String : Any]()
override func viewDidLoad() {
super.viewDidLoad()
depttDelegate = self
print("Departmens are : \(depttData)")
}
override func showDepttData(departments: [String : Any]){
// code
}
}
I not sure if needs override
key.
Protocol class
import UIKit
protocol sampleProtocol : class {
func getValues(valuess:String)
}
class sampleClass {
/// Shared Instance - So without creating a new Instance i can make use of its function
static let shared = sampleClass()
/// Delegate Object
var delegate : sampleProtocol?
/// Sample Func which will send data using protocol
func sendData(){
/// Called whnen data is to be Transmitted
delegate?.getValues(valuess: "output")
}
}
Usage -- Destination Class -- Your case ShowEmpVC
import UIKit
class sampleVC: UIViewController
{
override func viewDidLoad() {
super.viewDidLoad()
/// Make use of Shared Instance Created so, You need not to Re-allocate a New instance just to make use of Delegate
sampleClass.shared.delegate = self
}
}
/// Assign class to Protocol
extension sampleVC : sampleProtocol
{
/// Protocol stub
func getValues(valuess: String) {
/// Get Value
print(valuess)
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.