iOS   发布时间:2022-03-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了ios – 无法从处理程序访问类中存在的变量大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
import UIKit

class ViewController: UIViewController
{

    var icnNum : Int64 = 0

    let stopHandler =
        {
            (action:UIAlertAction!) -> Void in

            let num = icnNum
    }


    func showAlert( userStatus: String )
    {

        let alert = UIAlertController(title: "",message: "",preferredStyle: .alert)

        alert.title = "what you want to do?"

        alert.addAction(UIAlertAction(title: "Stop",style: .default,handler: stopHandler))

    }



}

我不知道如何从处理程序访问该icnNum.我得到了以下错误.我知道我无法直接访问该变量但是方式是什么.

实例成员’icnNum’不能用于’ViewController’类型

解决方法

在showAlert()函数中定义stopHandler闭包,它应该可以工作.

class ViewController: UIViewController
{
    var icnNum : Int64 = 0

        func showAlert( userStatus: String ) {
            let stopHandler = { (action:UIAlertAction!) -> Void in
                let num = self.icnNum
            }

            let alert = UIAlertController(title: "",preferredStyle: .Alert)
            alert.title = "what you want to do?"

            alert.addAction(UIAlertAction(title: "Stop",style: .Default,handler: stopHandler))
        }   
    }
}

编译器将强制您编写self.icnNum而不是icnNum,以明确闭包将持有对self的引用.

将stopHandler闭包存储为变量,就像在示例中一样,将创建循环引用.您的ViewController实例拥有对stopHandler闭包的强引用,闭包拥有对self的强引用(这是指向ViewController实例的指针).

如果要重用stopHandler,请更新

class ViewController: UIViewController {      
    var icnNum : Int64 = 0
    var stopHandler: ((action:UIAlertAction!) -> Void)?

    override init(nibName nibNameOrNil: String?,bundle nibBundLeorNil: NSBundle?) {
        super.init(nibName: nibNameOrNil,bundle: nibBundLeorNil)
        self.stopHandler = { [weak self] (action:UIAlertAction!) -> Void in
            let num = self?.icnNum
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


    func showAlert( userStatus: String )
    {
        let alert = UIAlertController(title: "",preferredStyle: .Alert)
        alert.title = "what you want to do?"

        alert.addAction(UIAlertAction(title: "Stop",handler: stopHandler))      
    }
}

设置stopHandler闭包时请注意[weak self].这将防止闭合保持对自身的强引用并避免上述循环引用.

更多细节:https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html#//apple_ref/doc/uid/TP40014097-CH20-ID57

大佬总结

以上是大佬教程为你收集整理的ios – 无法从处理程序访问类中存在的变量全部内容,希望文章能够帮你解决ios – 无法从处理程序访问类中存在的变量所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。