0

I am trying to query from parse.com and I would db receiving about 100 objects per time. I used the swift example code on their website, and the app doesn't build with that code. So I looked around and found that people were using code similar to this:

 var query = PFQuery(className:"posts")
    query.whereKey("post", equalTo: "true")
    query.findObjectsInBackgroundWithBlock({ (objects: [AnyObject]?, error: NSError?) -> Void in
        // do something


        self.myDataArray = objects as! [String]

    })

This does not work, because I am trying to convert PFObject to String

I would need to get the one one value from each object into a swift string array [String]. How do I get just the one text value, instead of the PFObject and how do I get it into the swift string array?

2 Answers 2

1

I don't speak swift very well, but the problem with the code is it's trying to cast the returned PFObject to a string, but you want to extract a string attribute, so (if you really want to do it):

for object in objects {
    var someString = object.valueForKey("someAttributeName") as String
    self.myDataArray.addObject(someString)
}

But please make sure you need to do this. I've noticed a lot of new parse/swift users (especially those who are populating tables) have the urge to discard the returned PFObjects in favor of just one of their attributes. Consider keeping the PFObjects and extracting the attributes later as you need them. You might find you'll need other attributes, too.

Sign up to request clarification or add additional context in comments.

Comments

0

For starters, I would definitely recommend using the "if let" pattern to qualify your incoming data. This is a nice Swift feature that will help avoid run-time errors.

var query = PFQuery(className:"posts")
query.whereKey("post", equalTo: "true")
query.findObjectsInBackgroundWithBlock(
{ (objects: [AnyObject]?, error: NSError?) -> Void in

    // check your incoming data and try to cast to array of "posts" objects.
    if let foundPosts = objects as? [posts]
    {   
        // iterate over posts and try to extract the attribute you're after
        for post in foundPosts
        {   
            // this won't crash if the value is nil
            if let foundString = post.objectForKey("keyForStringYouWant") as? String
            {
                // found a good data value and was able to cast to string, add it to your array!
                self.myDataArray.addObject(foundString)
            }
        }
})

1 Comment

This leaves this error. I tried changing it to a [PFObject] but then I got more errors below. "Use of undeclared type 'posts'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.