Fook
Fook

Reputation: 5550

Using a subclassed PFObject in tableView:cellForRowAtIndexPath

I've subclassed PFObject like so:

import UIKit
import Parse

class Post: PFObject, PFSubclassing {

    class func parseClassName() -> String {
        return "Post"
    }

}

Registering it in AppDelegate application:didFinishLaunchingWithOptions:

Post.registerSubclass()

I'm trying to use that class within my tableView:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell? {
    var cell = tableView.dequeueReusableCellWithIdentifier(postCellReuseIdentifier) as? PostCell
    if cell == nil {
        cell = PostCell(style: UITableViewCellStyle.Default, reuseIdentifier: postCellReuseIdentifier)
    }
    if let postCell = cell {
        // assign post to the cell
        postCell.post = object as! Post?
        // setup delegate
        postCell.delegate = self
        return postCell
    }

    return nil
}

I need to cast object as Post, but can't figure out how. I currently get this error:

Could not cast value of type 'PFObject' (0x10c856ef8) to 'MyApp.Post' (0x10c855670).

Upvotes: 1

Views: 45

Answers (2)

Fook
Fook

Reputation: 5550

I got this working. The following is required to subclass:

Add this to your bridging header:

#import <Parse/PFObject+Subclass.h>

Create your class:

class MyClass: PFObject, PFSubclassing {

    static func parseClassName() -> String {
        return "MyParseClass"
    }

}

Important: Make sure the class name returned in parseClassName() exactly matches the name of the class you created on Parse.com.

Register the subclass in AppDelegate:application:didFinishLaunchingWithOptions:

MyClass.registerSubclass()

You should now be able to cast a PFObject to your class.

Upvotes: 0

Mo Nazemi
Mo Nazemi

Reputation: 2717

First you need to make sure that your are subclassing a PFObject correctly by registering the instance. Also the downcast you are trying is impossible. You cannot downcast an instance of a base class to an instance of a derived class unless it is simply a derived instance stored as a base class.

Upvotes: 1

Related Questions