2015-10-26 64 views
0

你好iOS中發生異常問題Swift

我想問你一個IOS中使用Swift 2.0語言的代碼管理異常的問題。

我有以下代碼:

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,所以我試圖用我以前使用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) 
})) 

這樣做,我得到了以下的問題:

扔功能沒有發生調用嘗試表達內catch塊不可達...

我想問你,什麼是管理這種異常的正確方法是什麼?

在先進的感謝

+1

在Swift 2中處理錯誤是不是**意味着處理異常。請閱讀[docs](https://developer.apple.com/library/watchos/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID508)。 – Moritz

+0

謝謝,如果您必須管理此異常,您將使用哪些資源來避免此問題? –

回答

0

看看KeychainWrapper.h文件。沒有方法setValue:forKey:
相反,你應該使用mySetObject:forKey:
如果你想嘗試this教程。
乾杯。

+0

非常感謝你的幫助,我有你的想法我解決了這個問題,再次感謝你 –

+0

如果可能,請標記答案爲正確的。 – user3820674

+0

完成了!再次感謝你! –

0

好了,你不能因爲在編譯時這段代碼是不是想拋出一個異常編譯器的封裝內try-catch你的代碼。另外,Swift錯誤並不是例外,它們的作用就像NSError處理強制處理規則一樣。

+0

謝謝,但我正在讀一些關於NSError的內容,但在這種情況下我沒有找到使用它的方法,您是否有使用NSError避免異常的想法? –