我正在使用KVO作为已在初始化期间注册的子类PFObject
中的属性。
如果我使用1个物体,一切都很好。在第二个对象上我得到错误The class KVO_vs_PFObject.MyModel must be registered with registerSubclass before using Parse.
我需要多个对象来观察属性。
我尝试使用属性observer(didSet)
作为swift的替代方案,但编译器因为我使用托管属性而不会让我这么做。
有谁知道这段代码的用途是什么?
以下是我的代码:
import UIKit
import Parse
class MyModel : PFObject, PFSubclassing {
static func parseClassName() -> String {
return "MyModel"
}
override class func initialize() {
var onceToken : dispatch_once_t = 0;
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
@NSManaged var property1 : String?
}
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
var myObject = MyModel()
myObject.addObserver(self, forKeyPath: "property1", options: .New, context: nil)
myObject.property1 = "Hello"
myObject.removeObserver(self, forKeyPath: "property1")
// If I comment these 4 lines. myObject is happy observing the property.
var anotherObject = MyModel()
anotherObject.addObserver(self, forKeyPath: "property1", options: .New, context: nil)
anotherObject.property1 = "World"
anotherObject.removeObserver(self, forKeyPath: "property1")
}
override func observeValueForKeyPath(keyPath: String, ofObject object: AnyObject, change: [NSObject : AnyObject], context: UnsafeMutablePointer<Void>) {
var n : AnyObject? = change["new"]
switch keyPath {
case "property1" :
println("observed MyModel.property1 with value \(n)")
default :
break
}
}
}
答案 0 :(得分:1)
我最终根据相关帖子使用了计算属性而不是存储属性。 Subclassing PFObject in Swift
// @NSManaged var property1 : String?
var property1: String? {
get {
return self["property1"] as? String
}
set {
self["property1"] = newValue
println("observed MyModel.property1 with value \(newValue)")
}
}
答案 1 :(得分:1)
I have this in my AppDelegate in addition to the initialize(). There were some posts here that say that initialize() needs some kick-starting before getting invoked. Worth trying the following...
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launc
//-----------------Parse customizations------------------------------
// Enable storing and querying data from Local Datastore.
// Remove this line if you don't want to use Local Datastore features or want to use cachePolicy.
Parse.enableLocalDatastore()
// ****************************************************************************
// Uncomment this line if you want to enable Crash Reporting
// ParseCrashReporting.enable()
//
// Uncomment and fill in with your Parse credentials:
//This one is for the MyAppName Parse App
MyModel.registerSubclass()
// Rest of the stuff...