2015-10-16 92 views
0

想必我在這裏做錯了什麼,但是這段代碼看起來不起作用,我認爲它應該。任何人都可以發現我做錯了什麼,或者這可能是一個編譯器錯誤?爲什麼我無法捕捉到這個Swift異常?

一個異常不一定得到由它拋出不被逮住

enter image description here

根據拋出一個異常文檔:

Declaration 
SWIFT 
func valueForKey(_ key: String) -> AnyObject? 
OBJECTIVE-C 
- (id _Nullable)valueForKey:(NSString * _Nonnull)key 
Parameters 
key 
The name of one of the receiver's properties. 
Return Value 
The value of the property specified by key. 

Discussion 
If key is not a property defined by the model, the method raises an exception. This method is overridden by NSManagedObject to access the managed object’s generic dictionary storage unless the receiver’s class explicitly provides key-value coding compliant accessor methods for key. 
+0

@johnykumar,這不是多麼迅速的作品。你有一個'do'塊,你可以在呼叫站點使用'try'。這句話是正確的 –

+0

@GabrielePetronella謝謝兄弟我還沒有看到這是一個警告。我沒有太多家庭與迅速。 –

回答

4

因爲valueForKey不會引發任何異常。

看簽名

func valueForKey(_ key: String) -> AnyObject? 

它可以選擇返回AnyObject,所以如果你正在尋找的價值是不存在的,它只會返回nil

只是做

if let name = managedObject.valueForKey("displayName") { 
    ... 
} else if let name = managedObject.valueForKey("name") { 
    ... 
} 

底線,在迅速可以使用try只有當一個函數被明確標記爲拋出異常。編譯器會爲你檢查,但你也可以看看函數簽名來知道它是否拋出。

如果valueForKey是拋出一個異常,其函數簽名看起來像:

func valueForKey(_ key: String) throws -> AnyObject? 
+0

但它確實會拋出異常! NSUnknownKeyException –

+1

@DuncanGroenewald [文檔](https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ErrorHandling.html#//apple_ref/doc/uid/TP40014097-CH42-ID512 )解釋說,Swift 2的錯誤處理系統不是用來捕捉異常的。 – Moritz

+0

@EricD。嗯,好吧,現在這是我錯過的微妙之處.... –