使用另一个类方法中的参数调用类方法 [英] Call class method with argument from another class method

查看:647
本文介绍了使用另一个类方法中的参数调用类方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码文件 MyItemVC.swift 中,我定义了以下类和方法:

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
        }
    }
}

在这个类的其他地方,我调用cycleTimer(true)来启动计时器,使用cycleTimer(false)来停止它。

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

现在,我还想在我的 AppDelegate.swift 代码文件中使用常用方法,以便在应用程序从活动状态变为非活动状态时启动和停止计时器。但是我在从该类调用cycleTimer方法时遇到了麻烦。

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.

我在Stack Overflow上找到了一个答案,建议我可以像这样调用它:

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

但我收到此错误:


无法使用类型'(Bool)'的参数列表调用'cycleTimer'

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

如何在传递参数时从AppDelegate方法调用此方法?

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

感谢您的帮助。我意识到这一定是一个非常基本的问题,但我是编程并尝试使用Swift自学的新手。使用Swift而不是Obj-C的答案将不胜感激。

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.

推荐答案

您需要使用类功能才能使用就这样。

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.

这篇关于使用另一个类方法中的参数调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆