【问题标题】:Instance member cannot be used on type 'AppDelegate' [closed]实例成员不能用于类型“AppDelegate”[关闭]
【发布时间】:2021-03-23 22:56:54
【问题描述】:

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

【问题讨论】:

  • var之前添加static

标签: ios swift swift3


【解决方案1】:

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

class AppDelegate {
    static var itemGlobalArray = NSMutableArray()

    //...
}

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

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

【讨论】:

    【解决方案2】:

    我认为更好的方法是使用UIApplication.shared.delegate as? AppDelegate

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-27
      • 2016-05-23
      • 2016-01-01
      • 2016-09-09
      • 2020-01-16
      • 2017-06-25
      相关资源
      最近更新 更多