iosswiftparse-platformpfquerypfobject

Custom PFQuery and PFObject Connection in Swift 2.0


I've created a Custom class for both PFQuery and PFObject, where I just Inherit/extend with those classes to not having to worry about importing Parse everywhere I use a Query or an Object.

However, I've encountered a problem when trying to mix PFQuery and PFObject together with their custom class.

Heres my Custom Classes which should in theory now have the same properties and effects as PFObject and PFQuery, which they do in most cases.

class CustomQuery: PFQuery {
    override init(className:String) {
        super.init(className: className)
    }
}

class CustomObject: PFQbject {
    override init(className:String) {
        super.init(className: className)
    }
}

But I've encountered a problem when trying to use a "..InBackgroundWithBlock" function from the Query. Here's the code:

func GetAsyncObjects(query:CustomQuery, closure: (dataObjects:[CustomObject]) -> ()) {
    query.findObjectsInBackgroundWithBlock {(returnedObjects:[CustomObject]!, error:NSError?) -> Void in
        closure(dataObjects: returnedObjects!)
    }
}

The error occures at the second line of the block above, at "returnedObjects:[CustomObject]!" with the following error:

Cannot convert value of type '([CustomObject]!, NSError?) -> Void' to expected argument type 'PFQueryArrayResultBlock?'

I literally can't find to see the solution for this. Obviously changing CustomObject there to PFObject would work, but that makes the whole point of my CustomObject and CustomQuery obsolete.

Thanks!


Solution

  • Probably not the core issue here but your CustomObject subclasses from PFQbject (Notice there is a 'Q' instead of an 'O'). Also you will need to use PFObject in the closure inside of the GetAsyncObjects function because the signature of the block expects the returned objects to be of type [PFObject]?. You can circumvent the issue by doing something like this:

    // in CustomQuery class
    func GetAsyncObjects(closure: (dataObjects:[CustomObject]) -> ()) {
        self.findObjectsInBackgroundWithBlock {(returnedObjects:[PFObject]?, error:NSError?) -> Void in
            // explicitly cast to your custom object
            closure(dataObjects: returnedObjects as! [CustomObject])
        }
    }
    

    So in order for the closure to get an array of CustomObjects back, you can just cast the [PFObject]? data you get back from Parse to your desired array type, in this case [CustomObject].