HotDudeSmith HotDudeSmith - 2 months ago 8
iOS Question

Swift Issue with a Delegate among Two methods

I have a strange issue with same delegate(s) in among some methods in ViewController.swift. For example:

We have ViewController class with ToDoItemsDelegate such as this:

ViewController.swift

class ViewController: UIViewController, ToDoItemsDelegate {

override func viewDidLoad() {
super.viewDidLoad()

let todoitemsDelegate = ToDoItems(delegate: self)

print("Part 1: How many to do items?: \(todoitemsDelegate.items.count)")

secondPart()
}

func secondPart() {

let todoitemsDelegate = ToDoItems(delegate: self)

print("Part 2: How many to do items?: \(todoitemsDelegate.items.count)")
}
}


Output:

Part 1: How many to do items?: 5
Part 2: How many to do items?: 0


I don't understand why the secondPart() method doesn't give the right number like the first method "First Part: 5". No clue... It supposed to be work if you have a delegate to work among methods in ViewController. I tried to create a extra delegate and it behaved the same thing. Any idea what is wrong with it? Any suggestion appreciated. Thanks!

Edited (I added more details)

ToDoItems.swift

protocol ToDoItemsDelegate {

}

struct Item {

var title: String!
var description: Int!

}

class ToDoItems {

let delegate: ToDoItemsDelegate

init(delegate: ToDoItemsDelegate) {
self.delegate = delegate
}

var items = [Item]()

}

Answer

You should do the following. todoitemsDelegate is being declared outside of the functions and then assigned in viewDidLoad before it gets used. Now it will print the same value both times (0, as expected):

class ViewController: UIViewController, ToDoItemsDelegate {

     var todoitemsDelegate : ToDoItems? 

     override func viewDidLoad() {
         super.viewDidLoad()
         todoitemsDelegate = ToDoItems(delegate: self)

         print("Part 1: How many to do items?: \(todoitemsDelegate!.items.count)")

         secondPart()
     } 

     func secondPart() {

         print("Part 2: How many to do items?: \(todoitemsDelegate!.items.count)")
     }
}
Comments