Why custom delegate in iOS is not called - ios

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()

Related

Unable to call another class method using delegate in swift

I'm trying to call method of Class B from class A on the button tap event. But it does not work and below is my code.
// Viewcontroller
class ViewController: UIViewController {
#IBAction func btnClicked(_ sender: Any) {
var objA = A()
objA.delegate?.TestA()
}
}
// ClassA.swift
protocol TestA {
func TestA()
}
class A {
var delegate: TestA?
}
// ClassB.swift
class B : TestA {
func TestA() {
print(" Function A from b")
}
}
When tapping a button, function TestA() does not invoke.
I even tried the code below, but it also didn't work:
var objB = B()
var objA = A()
objA.delegate = objB
Because you instantiate instance of Class A using
var objA = A()
Clearly you haven't initialised delegate property in A because its optional its default value is nil
Now when you call
objA.delegate?.TestA()
delegate is nil hence function TestA will not be called
Suggestion
Always use camelCasing for declaring names of functions. So TestA() is incorrect rather use testA()
EDIT 1:
Tested this
#IBAction func btnClicked(_ sender: Any) {
let objA = A()
let objB = B()
objA.delegate = objB
objA.delegate?.TestA()
}
This is working fine what is the issue?
The objA.delegate is never assigned to an object, so it has an initial value of nil. The ? operator avoids calling a function on a nil object.
The answer by Sandeep Bhandari is right.
Some information for better understanding of Protocol and Delegates.
TestA is a protocol and an optional var delegate is defined in class A. This setup is right. The idea behind this setup is that any user of class A, in this case class B which conforms to protocol TestA gets a callback from class A. You need to call the delegate.testA() function from within class A.
The current implementation of ViewController is not at all benefiting from defining Protocol and Delegates.
To achieve proper usage, the class A cab be modified as follows:
protocol TestA {
func testA()
}
class A {
var delegate: TestA?
func process() {
// Do something and call delegate function to report it.
delegate?.testA()
}
}
And modify ViewController as follows (copied class B for completeness):
class ViewController: UIViewController {
#IBAction func btnClicked(_ sender: Any) {
var objA = A()
var objB = B()
objA.delegate = objB
objA.process()
}
}
// ClassB.swift
class B : TestA {
func TestA() {
print(" Function A from b")
}
}
Now function implemented in class B to conform to protocol TestA will be called when process() function on objA of class A is called.
This is better use of Protocol and Delegate. Hope this helps.

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()

Difference between class func vs only func

Whats the difference between these 2?
extension UIFont {
class func PrintFontFamily(font: FontName) {
let arr = UIFont.fontNamesForFamilyName(font.rawValue)
for name in arr {
println(name)
}
}
}
extension UIFont {
func PrintFontFamily(font: FontName) {
let arr = UIFont.fontNamesForFamilyName(font.rawValue)
for name in arr {
println(name)
}
}
}
A class func is a class method. It is called by sending a message to the class.
A func is an instance method. It is called by sending a message to an instance of the class.
The difference is that you call an class function like this:
UIFont.PrintFontFamily("test")
But 'constructing' the function with just the func keyword require create instance of the class and call the method on that instance:
var myFont = UIFont()
myFont.PrintFontFamily("test")
"Instance methods are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods by writing the keyword static before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method."
Instance method.
class Counter {
var count = 0
func increment() {
++count
}
func incrementBy(amount: Int) {
count += amount
}
func reset() {
count = 0
}
}
Usage:
let counter = Counter()
// the initial counter value is 0
counter.increment()
// the counter's value is now 1
counter.incrementBy(5)
// the counter's value is now 6
counter.reset()
// the counter's value is now 0
Type methods:
class SomeClass {
class func someTypeMethod() {
// type method implementation goes here
}
}
Usage:
SomeClass.someTypeMethod()
A class function is called with the class :
UIFont.PrintFontFamily("Helvetica Neue")
A non class function is a method you call from an instantiated object :
let font = UIFont(name: "Helvetica Neue", size: 30)
font.PrintFontFamily("Helvetica Neue")
In that case, you should use a class func
A class func is called on the type itself, while just func is called on the instance of that type.
An example:
class Test {
func test() {
}
}
To call test():
Test().test()
Here is the same thing with a class func
class Test {
class func test() {
}
}
To call test():
Test.test()
So, you don't have to make an instance of the class.
You can also call a static func. The difference between a static func and a class func is that static func translates into class final func which just means that subclasses cannot override the function.

Set delegate to class type not to instance in Swift

In Objective-C it was possible to set a class as a delegate (not an instance of a class but a pure class). Is it possible in Swift?
Yes it is
Declare a delegate variable to be a class type, not instance type.
I also make it optional, but we could also make it non-optional and pass it in the init method.
var delegate : Int.Type?
Code Example
class A {
static func sayHello() {
println("Hello")
}
}
class B {
var num = 10
var delegate : A.Type?
func hi() {
delegate?.sayHello()
}
}
var b = B()
b.delegate = A.self
b.hi()

Resources