Swift中的parse.com-是否可以将检索到的PFObject强制转换为子类? [英] parse.com in Swift - is it possible to cast retrieved PFObject as subclass?
问题描述
I've created a subclass of PFObject, basically following instructions on parse.com docs, and pinned the object locally. The parse docs don't seem to go into retrieving a PFObject subclass, and I'm wondering - is it possible to cast the retrieved object as the PFObject subclass. If so, how?
(我知道,如果不可能的话,可能有必要根据PFObject的检索到的属性重新实例化该子类.)
(I understand if it's not possible, it could be necessary to re-instantiate the subclass, based on the retrieved properties of the 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")
}
}
}
}
})
推荐答案
确保已在application:didFinishLaunchingWithOptions:
中注册了子类.就我而言,它不会将检索到的对象强制转换为PFObject子类.
Be sure you've registered subclass in application:didFinishLaunchingWithOptions:
. In my case, it doesn't cast the retrieved object as the PFObject subclass.
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
这篇关于Swift中的parse.com-是否可以将检索到的PFObject强制转换为子类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!