在Swift中的ios – parse.com – 是否可以将检索到的PFObject转换为子类?

前端之家收集整理的这篇文章主要介绍了在Swift中的ios – parse.com – 是否可以将检索到的PFObject转换为子类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经创建了一个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")
                    }
                }
            }
        }
    })
确保您已在应用程序中注册了子类: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

猜你在找的Swift相关文章