2016-04-15 15 views
-1

我有以下VC:錯誤時調用self.setValue(:forKey :)

class ViewController: UIViewController { 
    var platforms = [Platform]() 

    viewDidLoad() { 
     let newPlatforms = [Platform(0), Platform(1)] 
     self.setValue(newPlatforms, forKey: "platforms") 
    } 
} 

,但在運行時我得到崩潰錯誤:

Terminating app due to uncaught exception 'NSUnknownKeyException', reason: this class is not key value coding-compliant for the key platforms

但其確定當我使用,例如,字符串變量

class ViewController: UIViewController { 
    var string = "" 

    viewDidLoad() { 
     let newString = "Hello world" 
     self.setValue(newString, forKey: "string") 
    } 
} 

我真的需要這種鍵值編碼機制。這個例子特別簡化了。

+0

你爲什麼使用'setValue(_:forKey:)'? – nhgrif

+1

根據這篇文章,觀察值('platforms')需要從NSObject繼承,並且由於Swift數組甚至不是一個類,它是一個結構體,它可能無法被觀察到。 https://medium.com/proto-venture-technology/the-state-of-kvo-in-swift-aa5cb1e05cba#.tse34ddpo – EmilioPelaez

回答

1

platforms是一個數組(!),設置數組使用這個簡單的語法,不需要

class ViewController: UIViewController { 
    var platforms = [Platform]() 

    viewDidLoad() { 
     let newPlatforms = [Platform(0), Platform(1)] 
     platforms = newPlatforms 
    } 
} 

self


還是在第二個例子中分配String

string = newString 

基本上不使用valueForKey:/setValue:forKey:,除非你真的需要的KVC(鍵 - 值編碼)功能。

+0

我真的需要使用KVC。示例特別簡化了演示。 –

0

自我目前指的是ViewController。您應該使用字典來存儲鍵/值對。

0
var optionDictionary : NSMutableDictionary! 
optionDictionary.setValue(newPlatforms, forKey: "platforms") //or setObject if value is not work. 

試試這個。希望這將工作:)