Monday, April 15, 2024
HomeiOS Developmentios - Run a operate simply after initi() completes in Swift

ios – Run a operate simply after initi() completes in Swift


I’m testing to run delegation sample from initializers. Right here is my knowledge provider check class and its’ knowledge supply :

protocol MyClassDataSource : AnyObject{
    func returnString(string: String)
}

protocol MyClassProtocol: AnyObject {
    var dataSource : MyClassDataSource? { get set }
}

class MyClass : MyClassProtocol {
    weak var dataSource: MyClassDataSource?
    
    init() {
        print("1. My Class initialized")
        getString()
    }

    func getString() {
        let myString = "Hi there World"
        print("3. The getString func run")
        dataSource?.returnString(string: myString)
    }
}

I ship knowledge to my different class. Right here it’s :

class OtherClass : MyClassDataSource {
    
    weak var myClass : MyClassProtocol?
    
    init(myClass: MyClassProtocol?) {
        self.myClass = myClass
        self.myClass?.dataSource = self
        print("2. MyClass delegate set")
    }
    
    func returnString(string: String) {
        print("4. Delegate run and print the string: (string)")
    }
}

Then I initialize them :

let myClass = MyClass()
let otherClass = OtherClass(myClass: myClass)

I need to create my class and ship knowledge from MyClass to OtherClass. I needed to make use of init() features to set dataSource to self and likewise run a operate and ship knowledge. After all, it did not work. What I anticipated to see printed within the console :

  1. My Class initialized
  2. MyClass delegate set
  3. The getString() func run
  4. DataSource run in OtherClass and print the string: Hi there World

However getString() instantly run, earlier than setting or creating the OtherClass and prints this :

  1. My Class initialized
  2. The getString() func run
  3. MyClass delegate set

If I manually delay the getString() run, it really works :

    func getString() {
        let myString = "Hi there World"
        DispatchQueue.principal.asyncAfter(deadline: .now() + 0.1) { [weak self] in
            print("3. The getString func run")
            self?.dataSource?.returnString(string: myString)
        }
    }

So, my query is, how can I make it work? Can I set the delegate and ship knowledge between simply by initializing the lessons? Is it potential to do it one way or the other?



Supply hyperlink

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments