N
N
Neckvik2019-07-22 19:44:45
Swift
Neckvik, 2019-07-22 19:44:45

How to create custom events and call it in Swift?

Example , Class "A" and class "B".
In "A" we create an instance of "B".
For example, we start a timer in "B" and when it ends, some kind of "timer and" event occurred,
and class "A" is subscribed to this event via addTarget.
The question is how to create this "time end" event and how to indicate in the "B" class that it is subscribed (or has) to it and call it there.
The bottom line is I create my element in Xib, it’s not correct to throw out some event through the protocol, I want to be able to subscribe via addtarget or via storybord to take out @IBAction for "time end" for class B
How to do this or where to drip?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
briahas, 2019-07-22
@briahas

I'm not sure that I understood you correctly, but your style of presentation is simply twisting your brains.
I'll try from here:

Example , Class "A" and class "B".
In "A" we create an instance of "B".
For example, we start a timer in "B" and when it ends, some kind of "timer and" event occurred,
and class "A" is subscribed to this event via addTarget.
The question is how to create this "time end" event and how to indicate in class "B" that it is subscribed to it (or has it) and call it there.

Well, this can be done simply using delegates - an object of class A assigns itself a delegate to an object of class B when it (object B) is created. Next - when the "timer end" event occurs, we call the desired delegate method.
example:
class AClass {
    
    var b: BClass

    func timerFinished() {
        print("Ola-la!!!")
    }

    func startB() {
        b = BClass()
        b.delegate = self
        b.start()
    }
}

class BClass {
    
    var delegate: AClass?

    func start() {
        // как пример
        Timer.scheduledTimer(withTimeInterval: 0,
                             repeats: false,
                             block: { self.delegate?.timerFinished() })
    }
}

A
Aleksandr Govorukhin, 2019-08-05
@SnapSh0t

Why subscribe to an event via addTarget?
Study the material about Observers -> https://www.swiftbysundell.com/posts/observers-in-...
And it will not be superfluous to read about RxSwift -> https://habr.com/en/post/423603/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question