使用解析来查询Swift中的信息

时间:2015-04-13 03:35:05

标签: ios swift parse-platform

我目前正在尝试将解析数据库实现到Swift应用程序中。当您从解析查询时,我无法理解如何使用数据。这是我正在使用的查询:

    var query = PFQuery(className: "CompanyInfo")

    query.findObjectsInBackgroundWithBlock({
        (objects: [AnyObject]! , error: NSError!) -> Void in

        if error == nil{
            println("Successfully retrieved \(objects.count) specials.")
            println(objects[0])
        }else{
            println(error)
        }
    })

所以我知道这是有效的,因为它会将所有数据打印到控制台。

然后,当我执行objects[0]时,它打印出第一个。

我如何使用对象将数据设置到我的应用程序中?例如,如果我的解析类CompanyInfo中有一个标题部分,我如何获取该信息以供日后使用?

1 个答案:

答案 0 :(得分:0)

要将对象作为PFObjects来投射它们..

query.findObjectsInBackgroundWithBlock({
    (objects: [AnyObject]! , error: NSError!) -> Void in
        var myPFObjects = objects as? [PFObject] // now you have your array of pfobjects
})

获取pfobject的任何属性/列只需像这样调用它

var aPFObject = myPFObjects[0]
var title = aPFObject["title"] as? String

执行所有这些操作的更好方法是将pfobject子类化并通过类属性获取它们,这将产生以下代码:

子类..

class CompanyInfo: PFObject, PFSubclassing {

    var title: String? {
        get {
            return self["title"] as? String
        }
        set {
            self["title"] = newValue
        }
    }


    class func parseClassName() -> String! {
        return "CompanyInfo"
    }
}

以及您调用查询的代码:

var cpQuery = CompanyInfo.query()
cp.findObjectsInBackgroundWithBlock({
    (objects: [AnyObject]! , error: NSError!) -> Void in
    var myCompanyInfos = objects as? [CompanyInfo] //Directly cast them to your objects
    for cp in myCompanyInfos {
        println(cp.title) //print all the titles
    }
})
相关问题