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

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

问题描述

在我的代码文件 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)
}

但是我收到了这个错误:

But I got this error:

无法使用类型为(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.

推荐答案

你需要使用class函数才能这样使用.

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天全站免登陆