代码之家  ›  专栏  ›  技术社区  ›  David Robertson

停止方法的执行-Swift

  •  -1
  • David Robertson  · 技术社区  · 8 年前

    当我的watchKit应用程序进入后台时,它会触发委托方法 applicationWillResignActive 。方法文档表明,它可以用于暂停正在进行的任务。

    我有一个正在进行的方法,我希望通过使用外部方法来停止或破坏它。我该怎么做?

    实例

    func method1(){
    // performing some actions
    }
    
    func breakMethod1(){
    // running this method can stop (break) the execution of method1
    }
    
    1 回复  |  直到 8 年前
        1
  •  0
  •   dokun1    8 年前

    当然,这是假设您的应用程序已被架构为 breakMethod1() 肯定会取消中发生的操作 method1() .

    您应该为 NSNotification 在开始 方法1() 就像这样:

    let notificationCenter = NSNotificationCenter.defaultCenter()
    notificationCenter.addObserver(self, selector: "breakMethod1", name: UIApplicationWillResignActiveNotification, object: nil)
    

    为了清理,你也应该在这个观察者被触发后移除它:

    notificationCenter.removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)