Search code examples
iosuitableviewswiftparse-platformpfquery

Convert PFObject to NSString in Swift


the problem was getting the Comments for Feeds that are stored in different Classes on Parse, the actual Problem is getting the body out of the class as String.

I always get an error saying "PFObject is not a subtype of NSString"

var Comments = [PFObject]() 



var FeedObjects = self.Feeds[indexPath.row]
var CommentObjects = Comments

    var queryComment = PFQuery(className:"Comment")
        queryComment.whereKey("post", equalTo: FeedObjects)
        queryComment.selectKeys(["body", "author"])
        queryComment.orderByAscending("createdAt")
        queryComment.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
           if error == nil {
              var Comments = objects as [PFObject]
             self.Comments = Comments
  }
}
            println(Comments)

The output at this stage is

[<Comment: 0x7ffa98f2a560, objectId: efB384DliK, localId: (null)> {
    author = test;
    body = test;
}]

Thank you in advance.


Solution

  • Ok, to answer your question. The error you get is actually self-explanatory. You are trying to convert a PFObject to an NSString, which of course will not work.

    The error occurs when you call

    var Comment = CommentObjects["body"] as String!
    

    as you mentioned. This happens because you define CommentObjects like this:

    var CommentObjects = Comments
    

    and Comments is

    var Comments = [PFObject]() 
    

    This a) does not make much sense and b) causes your error, because CommentObjects is actually an array of PFObjects and thus CommentObjects["body"] returns a PFObject which you are trying to convert to a string.