Swift Parse - local datastore and displaying objects in a tableview

前端 未结 1 364
被撕碎了的回忆
被撕碎了的回忆 2021-01-24 02:26

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.

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 03:09

    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

    0 讨论(0)
提交回复
热议问题