Call class method with argument from another class

2019-02-27 16:23发布

问题:

In my code file MyItemVC.swift I have defined the following class and method:

class MyItemVC: UIViewController, UITextViewDelegate {

var timer = NSTimer()

    func cycleTimer(toggleOn: Bool) {
        if toggleOn == true {
            // Timer calls the replaceItem method every 3 seconds
            timer = NSTimer.scheduledTimerWithTimeInterval(3, target: self, selector: Selector("replaceItem"), userInfo: nil, repeats: true)
        } else {
            timer.invalidate() // stop the timer
        }
    }
}

Elsewhere in this class, I call cycleTimer(true) to start the timer and cycleTimer(false) to stop it.

Now, I also want to use the usual methods in my AppDelegate.swift code file to start and stop the timer when the app moves from active to inactive state. But I'm having trouble calling the cycleTimer method from that class.

I found an answer on Stack Overflow that suggested I could call it like this:

func applicationWillResignActive(application: UIApplication) {

    MyItemVC.cycleTimer()
}

But I also need to pass in an argument. So I tried calling it like this:

func applicationWillResignActive(application: UIApplication) {

    MyItemVC.cycleTimer(true)
}

But I got this error:

Cannot invoke 'cycleTimer' with an argument list of type '(Bool)'

How can I call this method from the AppDelegate methods while passing in an argument?

Thanks for the help. I realize this must be a very basic question but I'm new to programming and trying to teach myself using Swift. An answer using Swift rather than Obj-C would be greatly appreciated.

回答1:

You need to use class function to be able to use it this way.

class func cycleTimer(toggleOn: Bool) {

However, I'm not sure about thread safety.



回答2:

The function you have specified is not a class function. Add class keyword before func keyword.

The changed code:

class func cycleTimer

Note: In the previous versions of Swift you must use the following code (and also in C or other languages):

static func cycleTimer