iOS Swift中的异常管理问题

时间:2015-10-26 12:25:13

标签: ios swift exception keychain

您好

我想问一下使用Swift 2.0语言在IOS代码中进行异常管理的问题。

我有以下代码:

alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
     // Remove save value in Keychain
     let MyKeychainWrapper = KeychainWrapper()
     MyKeychainWrapper.setValue("Account", forKey: kSecAttrAccount as String)
     MyKeychainWrapper.setValue("password", forKey: kSecValueData as String)
     let loginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loginViewController") as! LoginViewController

     self.presentViewController(loginViewController, animated: true, completion: nil)
}))

问题是我在此代码中遇到以下异常:

2015-10-26 08:04:49.464 RapidSentryMaster[1907:25789] *** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<KeychainWrapper 0x7fe783922820> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key v_Data.'

我认为该异常是因为没有找到之前保存的任何KeyChain,所以我尝试以与以往相同的方式管理异常,例如在android或其他语言中使用try..catch

alert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
     // Remove save value in Keychain
     do{
         let MyKeychainWrapper = KeychainWrapper()
         try MyKeychainWrapper.setValue("Account", forKey: kSecAttrAccount as String)
         try MyKeychainWrapper.setValue("password", forKey: kSecValueData as String)
     }catch{

     }
     let loginViewController = self.storyboard?.instantiateViewControllerWithIdentifier("loginViewController") as! LoginViewController
     self.presentViewController(loginViewController, animated: true, completion: nil)
 }))

这样做我遇到了以下问题:

在try表达式和中没有调用抛出函数 捕获阻止无法访问......

我想问你,管理这样的异常的正确方法是什么?

先谢谢

2 个答案:

答案 0 :(得分:0)

好吧,您无法将代码封装在try-catch中,因为在编译时,此代码不会向编译器抛出异常。

此外,Swift错误不是例外,它们就像强制处理规则的NSError处理一样。

答案 1 :(得分:0)

查看KeychainWrapper.h文件。没有方法setValue:forKey:
相反,你应该使用mySetObject:forKey:
如果你想试试this教程 欢呼声。

相关问题