Brian Nezhad
Brian Nezhad

Reputation: 6258

Could not cast value of type '__NSCFNumber' () to 'NSArray' swift

Why can't cast NSCFNumber (Core Data) to NSArray?

Error:

Could not cast value of type '__NSCFNumber' (XXXXXXXX) to 'NSArray' (XXXXXXXX).

Code:

//Fetch Settings
    func fetchAccounSetting(){
        let entityDescription = NSEntityDescription.entityForName("UserSettings", inManagedObjectContext: Context!)
        let request = NSFetchRequest()
        //let data = UserSettings(entity: entityDescription!, insertIntoManagedObjectContext: Context)
        request.entity = entityDescription

        var dataObjects: [AnyObject]?

        do {
            dataObjects = try Context?.executeFetchRequest(request)
        } catch  let error as NSError {
            print(error)
            dataObjects = nil
        }

        for result in dataObjects as! [NSManagedObject] {
            let dataSelected = NSArray(array: result.valueForKey("favCategory")! as! NSArray)
            print(dataSelected)
        }

UPDATE: How can I receive the Count of dataSelected?

Upvotes: 1

Views: 7690

Answers (2)

Kelvin Lau
Kelvin Lau

Reputation: 6781

Core Data isn't capable of storing arrays or dictionaries in the first place. I remember encountering this problem before as I was learning.

AKA, your dataObjects array doesn't have anything that can be typecasted into an NSArray. The way to do this is to model a to-many relationship (which creates a Set), which can imitate an array.

Upvotes: 1

Aaron Brager
Aaron Brager

Reputation: 66242

result.valueForKey("favCategory")! is returning a number, but it looks like you're expecting an array.

Perhaps you meant:

let dataSelected = [result.valueForKey("favCategory")!]

If you know the type you're getting back you can optionally cast it:

let dataSelected = [result.valueForKey("favCategory")!]

if let dataSelected = dataSelected as? [NSNumber] {
    // dataSelected is of type [NSNumber] a.k.a. Array<NSNumber>
    print(dataSelected)
}

Upvotes: 0

Related Questions