Ios 实例成员不能用于类型';AppDelegate';
我在AppDelegate类中声明了一个变量itemGlobalArray,如下所示Ios 实例成员不能用于类型';AppDelegate';,ios,swift,swift3,Ios,Swift,Swift3,我在AppDelegate类中声明了一个变量itemGlobalArray,如下所示 var itemGlobalArray = NSMutableArray() if (AppDelegate.itemGlobalArray).count > 0 //Gives error here { let vc = UIStoryboard.init(name: "Main", bundle: Bundle.main).instanti
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 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)
}
您必须像静态成员一样声明它,静态成员可以在没有实例的情况下使用:
class AppDelegate {
static var itemGlobalArray = NSMutableArray()
//...
}
您可以在您的案例中使用它:
if (AppDelegate.itemGlobalArray).count > 0 { ... }
我认为更好的方法是使用
UIApplication.shared.delegate作为?AppDelegate
在var