2016-04-15 62 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. 

试试这个。希望这将工作:)