Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/xcode/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 试图从appdelegate中的单独类调用函数_Ios_Xcode_Swift_Appdelegate - Fatal编程技术网

Ios 试图从appdelegate中的单独类调用函数

Ios 试图从appdelegate中的单独类调用函数,ios,xcode,swift,appdelegate,Ios,Xcode,Swift,Appdelegate,我试图在应用程序关闭时使用userdefaults保存数组,但当我调用应用程序委托中的方法“调用中缺少参数'data'的参数”时,出现此错误 独立类的代码: func saveDataForKey(key: String, data: [Item]){ let arrayData = NSKeyedArchiver.archivedDataWithRootObject(data) NSUserDefaults.standardUserDefaults().setObject(

我试图在应用程序关闭时使用userdefaults保存数组,但当我调用应用程序委托中的方法“调用中缺少参数'data'的参数”时,出现此错误

独立类的代码:

func saveDataForKey(key: String, data: [Item]){
      let arrayData = NSKeyedArchiver.archivedDataWithRootObject(data)
    NSUserDefaults.standardUserDefaults().setObject(arrayData, forKey: ArrayKey)
}
来自应用程序代理的代码:

var ds = DataStore()//this is the separate class

func applicationDidEnterBackground(application: UIApplication) {

    ds.saveDataForKey(key: String, data: [Item])//this is where i get the error   
}

不要为此使用应用程序代理。请改用NSNotificationCenter。在您的类中(
DataStore
)注册以侦听系统通知,例如
UIApplicationIdentinterBackgroundNotification
。可以使用选择器或块。例如(选择器),您可以执行以下操作:

NSNotificationCenter.defaultCenter().addObserver(self,
        selector: "WRITE A METHOD AS EXPLAINED BELOW",
            name: UIApplicationDidEnterBackgroundNotification,
          object: nil)

在这种情况下,选择器是一种只能将
NSNotification
作为其唯一输入的方法。您可能需要用这种方法包装您的
saveDataForKey

in-app delegate,在调用saveDataForKey()时,您需要传递该函数调用的参数。为什么不传递参数?我认为“(key:String,data:[Item])是参数。我将使用什么来代替它?参数将是您希望保存在UserDefaults中的值此函数保存10个数组。那么,这个价值到底是什么呢?让我以不同的方式重复一下其他人所指出的。在app委托中,调用saveDataForKey()时,您没有传递参数,只是重复函数签名。在Swift(或任何其他语言)中,这不是正确的语法。此外,您不使用应用程序委托执行此操作。您应该始终更喜欢使用NSNotificationCenter。