首页 > 解决方案 > 实例成员不能用于“AppDelegate”类型

问题描述

我在 AppDelegate 类中声明了一个变量 itemGlobalArray,如下所示

var itemGlobalArray = NSMutableArray()

并尝试在如下视图控制器中使用它

if (AppDelegate.itemGlobalArray).count > 0 //Gives error here
        {
            let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "BasketVC") as? BasketVC
            self.navigationController?.pushViewController(vc!, animated: true)
        }
        else {
            let alert = UIAlertController(title: "Alert", message: "cart Empty", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { action in
                switch action.style{
                case .default:
                    print("default")
                    
                case .cancel:
                    print("cancel")
                    
                case .destructive:
                    print("destructive")
                    
                    
                }}))
            self.present(alert, animated: true, completion: nil)
        }

标签: iosswiftswift3

解决方案


您必须像静态成员一样声明它,静态成员可以在没有实例的情况下使用:

class AppDelegate {
    static var itemGlobalArray = NSMutableArray()

    //...
}

比你可以在你的情况下使用它:

if (AppDelegate.itemGlobalArray).count > 0 { ... }

推荐阅读