Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PFSubclassing with array pointer and swift 1.2 - fatal error: NSArray element failed to match the Swift Array Element type

With swift 1.2, I can no longer retrieve an array of poiter with parse subclass and downcasting it with another parse subclass.

I always found the error:

fatal error: NSArray element failed to match the Swift Array Element type

Do you have an idea or it may come?

The code:

import Foundation

class ShotModel : PFObject, PFSubclassing {

    /**
    * MARK: Properties
    */
    @NSManaged var name: String

    @NSManaged var pics: [PicModel]


    override class func initialize() {
        var onceToken : dispatch_once_t = 0;
        dispatch_once(&onceToken) {
            self.registerSubclass()
        }
    }

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

}

import Foundation

class PicModel : PFObject, PFSubclassing {

    /**
    * MARK: Properties
    */
    @NSManaged var name: String


    override class func initialize() {
        var onceToken : dispatch_once_t = 0;
        dispatch_once(&onceToken) {
            self.registerSubclass()
        }
    }

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

}

// this cause error

var shot: ShotModel = // a shot model get with fetchInBackgroundWithBlock

shot.pics // fatal error: NSArray element failed to match the Swift Array Element type

Thanks for your time

like image 637
Antoine Lenoir Avatar asked Mar 13 '15 09:03

Antoine Lenoir


3 Answers

The problem come from this part of code :

override class func initialize() {
    var onceToken : dispatch_once_t = 0;
    dispatch_once(&onceToken) {
        self.registerSubclass()
    }
}

registerSubclass() for ShotModel is called before registerSubclass() for PicModel.

I've resolved with this in AppDelegate :

PicModel.registerSubclass()
ShotModel.registerSubclass()
like image 64
Antoine Lenoir Avatar answered Nov 20 '22 03:11

Antoine Lenoir


The problem lies to the fact that ShotModel is registered as a subclass before PicModel. To invert that we can call PicModel initialisation the initialisation of ShotModel.

This way we keep the suggested solution by parse and make sure that classes are registered in the correct order.

class ShotModel : PFObject, PFSubclassing {

    /**
    * MARK: Properties
    */
    @NSManaged var name: String

    @NSManaged var pics: [PicModel]


    override class func initialize() {
        var onceToken : dispatch_once_t = 0;
        dispatch_once(&onceToken) {
            PicModel.initialize()
            self.registerSubclass()
        }
    }
like image 4
zirinisp Avatar answered Nov 20 '22 02:11

zirinisp


Somehow I had to also init the object after registering in AppDelegate:

PicModel.registerSubclass()
PicModel()
ShotModel.registerSubclass()
ShotModel()
like image 1
Aviel Gross Avatar answered Nov 20 '22 02:11

Aviel Gross