我已经创建了PFObject的子类,基本上遵循了parse.com docs上的指令,并在本地固定了对象。解析文档似乎没有进入检索PFObject子类,我想知道 - 是否可以将检索到的对象转换为PFObject子类。如果是这样,怎么样?
(我知道如果不可能,可能需要根据检索到的PFObject属性重新实例化子类。)
let query = PFQuery(className:Armor.parseClassName())
query.fromLocalDatastore()
query.findObjectsInBackgroundWithBlock({
(objects:[AnyObject]?, error: NSError?) in
if let error = error {
// There was an error
} else {
if let objects = objects as? [PFObject] {
for object in objects {
//This println is outputting to the console:
println("PFObject object retrieved")
if let object = object as? Armor {
//This println is NOT outputting to the console:
println("PFObject object cast as Armor")
}
}
}
}
})
答案 0 :(得分:12)
请确保您已在application:didFinishLaunchingWithOptions:
中注册了子类。就我而言,它不会将检索到的对象强制转换为PFObject子类。
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Armor.registerSubclass()
Parse.enableLocalDatastore()
Parse.setApplicationId(..., clientKey: ...)
return true
}
<强> AppDelegate.swift 强>
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
CatsObject.registerSubclass()
Parse.enableLocalDatastore()
Parse.setApplicationId("...", clientKey: "...")
return true
}
<强> CatsObject.swift 强>
import Foundation
class CatsObject: PFObject, PFSubclassing {
static func parseClassName() -> String {
return "Cat"
}
}
<强> CatViewController.swift 强>
override func viewDidLoad() {
queryData()
}
func queryData() {
let query = PFQuery(className: CatsObject.parseClassName())
query.fromLocalDatastore()
query.findObjectsInBackgroundWithBlock({
(objects:[AnyObject]?, error: NSError?) in
if let error = error {
// There was an error
} else {
println("count local objects = \(objects?.count)")
if let objects = objects as? [PFObject] {
for object in objects {
println("PFObject object retrieved")
if object is CatsObject {
println("object is CatsObject subclass")
}
if let object = object as? CatsObject {
println("PFObject object cast as CatsObject")
}
}
}
}
})
}
控制台输出
count local objects = Optional(10)
PFObject object retrieved
object is CatsObject subclass
PFObject object cast as CatsObject