How do i make singleton class as delegator in swift3 - ios

I have a singleton class as shown in below code snippet .
protocol EmpLoginDelegate {
func empLoginSuccess()
func empLoginFailed()
}
class CommunicationModule {
static let sharedInstance = CommunicationModule()
private init() {
}
var empLoginDelegate:EmpLoginDelegate?
func test(){
self.empLoginDelegate?.empLoginSuccess()
}
}
My delegate class is shown in below code snippet.
extension LoginViewController: EmpLoginDelegate{
func empLoginSuccess(){
wrongAttempts = 0
loginSuccess = true
print("EmpLoginIsSuccess")
performSegue(withIdentifier: "attendanceView", sender: self)
}
func empLoginFailed(){
wrongAttempts = wrongAttempts + 1
userNameTextField.shake(count: 3, for: 0.3, withTranslation: 10)
passwordTextField.shake(count: 3, for: 0.3, withTranslation: 10)
loginSuccess = false
loginAlert(alertTitle: "Invalid Credentials", alertMsg: "Your employee id or password is not correct")
}
}
When i call test function emploginSuccess() method does not get called. Test function is executed successfully with out any error.
I thought that problem is empLoginDelegate is not initialised in my code, so i had tried possible ways to initialise it as self but nothing worked for me. Is there any other way to use delegation pattern in singleton class in swift3(iOS 10.3.1).

Make sure you are communicating with the singleton properly. To set your instance of LoginViewController as the empLoginDelegate, call:
CommunicationModule.sharedInstance.empLoginDelegate = self
from a method inside of LoginViewController.

I think This method is good, for me that is best way
final class Singleton {
// Can't init is singleton
private init() { }
//MARK: Shared Instance
static let shared: Singleton = Singleton()
}

Related

Accessing a Running Instance of a Class Swift

I have class A in file A and class B in file B. In class B, I want to access the running instance of class A, in order to run a function located in it. Both classes are connected to view controllers. I do not want to create a new instance of class A as in classAInstance = classA(), but rather access the instance of class A that my app is already running. Any help would be appreciated.
Here is part of my code in class A:
Class A {
func reloadTableView() {
self.CardsTableView.reloadData()
}
}
And here is part of my code in class B:
Class B {
#IBAction func saveButton(_ sender: UIButton) {
// here is where I want to call reloadTableView() from class A
}
}
The quick and dirty method I might use would be where you have some singleton where you can store the current instances of your classes.
Example:
class EnvironmentUtility {
private static var instance: EnvironmentUtility?
internal class func shared() -> EnvironmentUtility {
guard let currentInstance = instance else {
instance = EnvironmentUtility()
return instance!
}
return currentInstance
}
var myClassA: ClassA? = nil
var myClassB: ClassB? = nil
}
Then in the viewDidLoad (Or wherever else you like that a new instance is being made) of the those ViewControllers/Classes:
class ClassA: UIViewController {
…
override func viewDidLoad() {
…
EnvironmentUtility.shared().myClassA = self
}
…
}
Later in ClassB you could then:
class ClassB: UIViewController {
…
#IBAction func saveButton(_ sender: UIButton) {
EnvironmentUtility.shared().myClassA.reloadTable()
}
…
}
This isn’t the prettiest or Swifty-est way of doing it, but quick and dirty.
If you want to write a better solution I would suggest looking at the MVVM-C Swift architectural pattern (I use this pattern myself). In this architecture you will have access to a Coordinator that overseas viewController transitions and you can also track current instances of your ViewControllers/Classes in a much more elegant way.
Here is a crash course in MVVM-C: https://marcosantadev.com/mvvmc-with-swift/

Weak delegate becomes nil

In my app I'm using delegates, so that I can read the data when ever it's ready.
I'm calling a delegate from two classes. Here is my code
protocol MyDelegate: class {
func getData()
}
class MyDelegateCalss {
weak var delegate: MyDelegate?
func loadData() {
// doing some actions
if(self.delegate != nil){
self.delegate!.getData!()
}
}
}
In one class I'm loading this method in tableview numberOfSections delegate method.
class A: UIViewController, MyDelegate {
func somefunc(){
let mydelegatecls : MyDelegateCalss = MyDelegateCalss()
mydelegatecls.delegate = self
mydelegatecls.loadData()
}
func getData(){
// Doing some actions
}
}
This method I'm loading from another calss.
class B: UIViewController, MyDelegate {
open func testfunc(){
let mydelegatecls : MyDelegateCalss = MyDelegateCalss()
mydelegatecls.delegate = self
mydelegatecls.loadData()
}
func getData(){
// doing some other stuff
}
}
class C: UIViewController {
func testfunc(){
let b : B = B()
b.testfunc()
}
}
Here from class A my delegate is working fine. and I'm able to see getData method is calling .
from Class B, the delegate becomes nil and unable to see getData method is called
If I make the delegate reference its working fine. But that will cause memory leak.
How can handle this case ?
Your delegate var is declared as weak. If nothing keep a strong reference on the object you assign as the delegate (implementing MyDelegate), your delegate will pass to nil as soon as the object is released (eg. the end of the scope where you instantiate it).
Some good read: https://cocoacasts.com/how-to-break-a-strong-reference-cycle/

delegate in swift 3 does not perform view related codes

In my project I have some delegates that works fine with returning data but I want to add some subview or do any anything in the delegate method on the receiving end nothing happen but the other codes that are in the same method are OK!
My other question is also realated to delegates :
This happens for some delegates. The delegate does not respond but I found a very strange fix on the web and I need to know why this happens and why this fix works!
My First View :
protocol SomeDelegate {
func someMethod()
}
class FirstViewClass {
//in init or didLoad method
var delegate: SomeDelegate?
// THIS DELEGATE WON'T WORK BUT WHEN I ADD THIS LINE IT WORKS FINE( IT STILL HAS THE ABOVE PROBLEM)
self.delegate = SecondViewClass()
//in some custom method
self.delegate?.someMethod();
}
My Second View:
class SecondViewClass : SomeDelegate {
var firstView = FirstViewClass()
// this is in init or didLoad method
firstView.delegate = self
//this is in some custom method
someMethod()
}
A simple working prototype:
protocol SomeDelegate {
func someMethod()
}
class FirstViewClass {
var delegate: SomeDelegate?
}
class SecondViewClass : SomeDelegate {
var firstView = FirstViewClass()
func someMethod() {
print("called via delegate")
}
}
var firstClass = FirstViewClass()
var secondClass = SecondViewClass()
firstClass.delegate = secondClass
firstClass.delegate?.someMethod()

Swift Delegate from Singleton not working

I'm trying to implement SharedInstanceDelegate in App class. I have no idea why the functions under the protocol are not being called.
This is my Protocol and class.
class App {
let sharedInstance = SharedInstance.shared
init() {
self.sharedInstance.delegate = self
}
}
extension App: SharedInstanceDelegate {
func1() { } // this is not executed
func2() { }
}
protocol SharedInstanceDelegate: class {
func1()
func2()
}
class SharedInstance {
static let shared = SharedInstance()
weak var delegate: SharedInstanceDelegate?
private init() { }
func method1() {
self.delegate?.func1() // this is executed
}
}
I believe you meant to make SharedInstanceDelegate a protocol, but you've made it a class. In either case, App does not conform/inherit SharedInstanceDelegate, so it's not clear how this would even compile.
Here is how I would implement your code to work with the delegate:
class App {
let sharedInstance = SharedInstance.shared
init() {
self.sharedInstance.delegate = self
}
}
extension App: SharedInstanceDelegate {
func func1() { } // this will run now
func func2() { }
}
protocol SharedInstanceDelegate {
func func1()
func func2()
}
class SharedInstance {
static let shared = SharedInstance()
var delegate: SharedInstanceDelegate?
private init() { }
func method1() {
self.delegate?.func1() // this is executed
}
}
Still no idea why this was happening, but cleaning the project fixed this. This is very strange. I have other delegates that call successfully.
Your code could work but it depends on how you are calling func1(). Calling it like this:
let testinstance = App().sharedInstance
testinstance.delegate?.func1()
will not work because you are not holding on to the App object. In this case the App object is the delegate, but because its a weak member and no one is retaining it, it gets released right away.
If you call it like this:
let testapp = App()
testapp.sharedInstance.delegate?.func1()
it works. In this case the App object is being retained and is still around when func1() is called.
Either way the way these classes are related is confusing to me. Why have a separate SharedInstance class at all?

Why custom delegate in iOS is not called

I am trying to create a custom delegate using playground in swift. However the doSomething method is not being called through callback.
It seems that delegate?.doSomething() does not fire to the XYZ class doSomething method.
Thanks in advance!
import UIKit
#objc protocol RequestDelegate
{
func doSomething();
optional func requestPrinting(item : String,id : Int)
}
class ABC
{
var delegate : RequestDelegate?
func executerequest() {
delegate?.doSomething()
println("ok delegate method will be calling")
}
}
class XYZ : RequestDelegate
{
init()
{
var a = ABC()
a.delegate = self
}
func doSomething() {
println("this is the protocol method")
}
}
var a = ABC()
a.executerequest()
It seems that delegate?.doSomething() does not fire to the XYZ class
doSomething method.
That is correct. class ABC has an optional delegate property, but the value of
the property is nowhere set. So the delegate is nil
and therefore the optional chaining
delegate?.doSomething()
simply does nothing. Also you have defined a class XYZ but
not created any instances of that class.
If you set the delegate of a to an instance of XYZ then
it will work as expected:
var a = ABC()
a.delegate = XYZ()
a.executerequest()

Resources