Swift Parse - 本地数据存储区并在tableview中显示对象 [英] Swift Parse - local datastore and displaying objects in a tableview

查看:122
本文介绍了Swift Parse - 本地数据存储区并在tableview中显示对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建和应用程序,使用解析将对象保存在本地数据存储区中。然后我运行一个查询来检索本地数据存储区中的对象,它工作正常。但是,我想获取对象及其中的内容,并根据存储在解析本地数据存储对象中的项目在表视图单元格中设置一些标签。例如,我创建一个具有objectID,name,date,location等属性的对象。我想做的是在主屏幕上有一个表格视图,显示名称,日期,位置等。保存在每个单元格中的标签中的本地数据存储区中的每个项目。



我知道我正确保存它:

  //解析位置对象

让parseLighthouse = PFObject(className:ParseLighthouse)
parseLighthouse.setObject(PFUser.currentUser()! ,forKey:User)
parseLighthouse [Name] = self.placeTitle.text
parseLighthouse [Note] = self.placeNote.text
parseLighthouse [Locality] = self.placeDisplay.text!
parseLighthouse [ LATT] = self.map.region.center.latitude
parseLighthouse [ 茇] = self.map.region.center.longitude
parseLighthouse [ LattDelta] = 0.5
parseLighthouse [ LongiDelta] = 0.5
parseLighthouse [ 日期= dateInFormat
parseLighthouse.pinInBackground()
parseLighthouse.saveInBackgroundWithBlock {(成功:布尔,错误: NSError?) - >无效
println(对象已保存.ID = \(parseLighthouse.objectId))
}

当我运行查询时,我可以通过运行println(object.objectForKey(Name))来访问属性。

  func performQuery(){
let query = PFQuery(className:ParseLighthouse)

query.fromLocalDatastore()
query.whereKey( User,equalTo:PFUser.currentUser()!)
query.findObjectsInBackgroundWithBlock {(objects,error) - >如果错误== nil {
//找到成功,则
无效。
println(成功检索\(objects!.count)灯塔。)
//使用找到的对象执行某些操作
如果让light =对象为? [PFObject] {
for light in light {
println(object.objectId)
println(object.objectForKey(Name))



}
}
} else {
//记录失败的详细信息
println(错误:\(错误!)\(错误!.userInfo !))
}
}

因为在运行查询时,我按预期返回对象ID和名称。



成功检索2个灯塔。
可选(A3OROVAMIj)
可选(快乐)
可选(bbyqPZDg8W)
可选(日期测试)



<我想要做的是获取parse对象本地数据存储中的name字段,这是表视图控制器中单元格上的标签名称。



我不知道如何从对象访问该信息,并正确设置标签。



有谁知道这是怎么回事?

解决方案

它总是一个好主意,以避免指针大声笑...所以为什么不保存特定对象的用户ID或用户名..
所以改变这一行:

  parseLighthouse.setObject(PFUser.currentUser()!, forKey:User)

TO

  parseLighthouse [username] = PFUser.currentUser()。username 

回答



现在让我们创建一个结构在Controller类之外包含 objectID和Name

  struct Data 
{
var名称:字符串!
var id:String!
}

然后在Controller类中,全局声明以下代码行

  var ArrayToPopulateCells = [Data]()

然后您的查询函数将如下所示:

  func performQuery(){
let query = PFQuery(className:ParseLighthouse)

query.fromLocalDatastore()
query.whereKey(User,equalTo:PFUser.currentUser()!)
query .findObjectsInBackgroundWithBlock {(objects,error) - >如果错误== nil {
//找到成功,则
无效。
print(成功检索\(objects!.count)灯塔。)
//使用找到的对象执行某些操作
如果让light =对象为? [PFObject] {
for light in light {
print(object.objectId)
print(object.objectForKey(Name))
var singleData = Data()
singleData.id = object.objectId
singleData.Name = object [Name] as! String

self.ArrayToPopulateCells.append(singleData)


}
}
} else {
//日志详细信息失败
打印(错误:\(错误!)\(错误!.userInfo))
}
}

在tableView numberOfRowinSection()

  return ArrayToPopulateCells.count 

在cellForRowAtIndexPath()

  var data = ArrayToPopulateCells [indexPath.row] 
cell.textlabel.text = data.objectID
cell .detailLabel.text = data.Name

应该是VOila


I am building and app that saves an object in the local datastore with parse. I then run a query to retrieve the objects that are in the local datastore and it is working fine. however, I would like to grab the object, and the contents in it, and set some labels in a table view cell based on the items that are stored in the parse local data store object. for example, i make an object with attributes like "objectID", "name", "date", "location". what i'd like to do is to have a table view on the home screen that displays the name, date, location ...etc. of each item that was saved in local datastore in labels in each cell.

i know that im saving it correctly:

// parse location object

    let parseLighthouse = PFObject(className: "ParseLighthouse")
    parseLighthouse.setObject(PFUser.currentUser()!, forKey: "User")
            parseLighthouse["Name"] = self.placeTitle.text
            parseLighthouse["Note"] = self.placeNote.text
            parseLighthouse["Locality"] = self.placeDisplay.text!
            parseLighthouse["Latt"] = self.map.region.center.latitude
            parseLighthouse["Longi"] = self.map.region.center.longitude
            parseLighthouse["LattDelta"] = 0.5
            parseLighthouse["LongiDelta"] = 0.5
            parseLighthouse["Date"] = dateInFormat
            parseLighthouse.pinInBackground()
            parseLighthouse.saveInBackgroundWithBlock { (success: Bool, error: NSError?) -> Void in
                println("Object has been saved. ID = \(parseLighthouse.objectId)")
            }

and when i run the query, im able to access the attributes by running println(object.objectForKey("Name"))

func performQuery() {
    let query = PFQuery(className: "ParseLighthouse")

    query.fromLocalDatastore()
    query.whereKey("User", equalTo: PFUser.currentUser()!)
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if error == nil {
            // The find succeeded.
            println("Successfully retrieved \(objects!.count) lighthouses.")
            // Do something with the found objects
            if let light = objects as? [PFObject] {
                for object in light {
                    println(object.objectId)
                    println(object.objectForKey("Name"))



                }
            }
        } else {
            // Log details of the failure
            println("Error: \(error!) \(error!.userInfo!)")
        }
    }

because when running the query, i get back the object id and name as expected.

Successfully retrieved 2 lighthouses. Optional("A3OROVAMIj") Optional(happy) Optional("bbyqPZDg8W") Optional(date test)

what I would like to do is grab the name field within the parse object local data store, and that be the name of the label on a cell in a table view controller.

i dont know how to access that info from the object, and set the label correctly.

does anyone know how this is possible?

解决方案

It's always a good idea to avoid pointer lol ... so why not saving the userid or username with the specific object.. so change this line:

 parseLighthouse.setObject(PFUser.currentUser()!, forKey: "User")

TO

 parseLighthouse["username"] = PFUser.currentUser().username

Answer

NOW let's create a struct that contains the objectID and the Name outside of your Controller Class.

struct Data
{
var Name:String!
var id:String!
}

then inside of the Controller class, declare the following line of code globally

 var ArrayToPopulateCells = [Data]()

Then your query function will look like :

 func performQuery() {
    let query = PFQuery(className: "ParseLighthouse")

    query.fromLocalDatastore()
    query.whereKey("User", equalTo: PFUser.currentUser()!)
    query.findObjectsInBackgroundWithBlock { (objects, error) -> Void in
        if error == nil {
            // The find succeeded.
            print("Successfully retrieved \(objects!.count) lighthouses.")
            // Do something with the found objects
            if let light = objects as? [PFObject] {
                for object in light {
                    print(object.objectId)
                    print(object.objectForKey("Name"))
                    var singleData = Data()
                    singleData.id = object.objectId
                    singleData.Name = object["Name"] as! String

                    self.ArrayToPopulateCells.append(singleData)


                }
            }
        } else {
            // Log details of the failure
            print("Error: \(error!) \(error!.userInfo)")
        }
    }

In the tableView numberOfRowinSection()

return ArrayToPopulateCells.count

In the cellForRowAtIndexPath()

       var data = ArrayToPopulateCells[indexPath.row]
       cell.textlabel.text = data.objectID
       cell.detailLabel.text = data.Name

VOila that should be it

这篇关于Swift Parse - 本地数据存储区并在tableview中显示对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆