問題是is_Block在SKNode上不存在。
setValue forUndefinedKey
默認會引發NSUndefinedKeyException。
如果你有一個子類,你可以重載這個函數來做你想做的事情。
請參閱https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/KeyValueCoding/Articles/BasicPrinciples.html以更好地理解關鍵值編碼。
如果你想SKNode有一個名爲is_Block的自定義變量,你將不得不爲SKNode創建一個擴展,並創建一個屬性爲你存儲這些數據。
import Foundation
import SpriteKit
import ObjectiveC
extension SKNode{
var isBlock: Bool {
get {
var key = "isBlock";
guard let block = objc_getAssociatedObject(self, &key) as? Bool
else{
print("Error");
return false
}
print("Success");
return block
}
set(newValue) {
var key = "isBlock";
print("Setting \(newValue)")
objc_setAssociatedObject(self, &key, newValue , objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
測試在操場:
import Foundation
import SpriteKit
import ObjectiveC
extension SKNode{
var isBlock: Bool {
get {
var key = "isBlock";
guard let block = objc_getAssociatedObject(self, &key) as? Bool
else{
print("Error");
return false
}
print("Success");
return block
}
set(newValue) {
var key = "isBlock";
print("Setting \(newValue)")
objc_setAssociatedObject(self, &key, newValue , objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
}
}
}
let a = SKNode()
let b = SKNode()
a.isBlock = false
b.isBlock = true
print ("\(a.isBlock), \(b.isBlock)")
b.isBlock = false
a.isBlock = true
print ("\(b.isBlock), \(a.isBlock)")
請告訴我這個問題? –