Core Data: Could Not Cast Value of Type 'Mytype_Mytype_2' to Mytype

Core Data Migration: Could not cast value of type 'NSManagedObject_MyType' to 'MyModule.MyType'

The reason is that during migration, you should not be using instances of NSManagedObject subclasses. You need to express all of these in the form of NSManagedObject. So the code above must become:

class LegacyToModernPolicy: NSEntityMigrationPolicy {

static func find(entityName: String,
in context: NSManagedObjectContext,
sortDescriptors: [NSSortDescriptor],
with predicate: NSPredicate? = nil,
limit: Int? = nil) throws -> [NSManagedObject] {

let fetchRequest: NSFetchRequest<NSManagedObject> = NSFetchRequest(entityName: entityName)
fetchRequest.predicate = predicate
fetchRequest.sortDescriptors = sortDescriptors
if let limit = limit {
fetchRequest.fetchLimit = limit
}

do {
let results = try context.fetch(fetchRequest)
return results
} catch {
log.error("Error fetching: \(error.localizedDescription)")
throw error
}
}

func libraryForManager(_ manager: NSMigrationManager) -> NSManagedObject {

do {
var library: NSManagedObject? = try LegacyToModernPolicy.find(entityName: Library.entity().name!,
in: manager.destinationContext,
sortDescriptors: [NSSortDescriptor(key: "filename", ascending: true)],
with: nil,
limit: 1).first
if library == nil {
let dInstance = NSEntityDescription.insertNewObject(forEntityName: Library.entity().name!, into: manager.destinationContext)

// awakeFromInsert is not called, so I have to do the things I did there, here:
dInstance.setValue(Library.libraryFilename, forKey: #keyPath(Library.filename))
dInstance.setValue(NSDate(timeIntervalSince1970: 0), forKey: #keyPath(Library.updatedAt))
library = dInstance
}

return library!

} catch {
fatalError("Not sure why this is failing!")
}
}}

You can read more about my less-than-fun experiences with Core Data Migrations here.

Could not cast value of type 'NSKnownKeysDictionary1' () to '' ()

In order to get an array of dictionaries from the fetch request
you must do two things:

  • Set fetchRequest.resultType = .dictionaryResultType (as you already did), and
  • declare the fetch request as NSFetchRequest<NSDictionary> instead of NSFetchRequest<YourEntity>.

Example:

let fetchRequest = NSFetchRequest<NSDictionary>(entityName:"Event")
fetchRequest.resultType = .dictionaryResultType

// Optionally, to get only specific properties:
fetchRequest.propertiesToFetch = [ "prop1", "prop2" ]

do {
let records = try context.fetch(fetchRequest)
print(records)
} catch {
print("Core Data fetch failed:", error.localizedDescription)
}

Now records has the type [NSDictionary] and will contain an
array with dictionary representations of the fetched objects.

Could not cast value of type '__NSCFSet' (0x109b56408) to 'NSArray' Swift 4

The data is not an array, it's a set. And use proper keys to access the data.

var managedObjectContext: NSManagedObjectContext! {
didSet {
NotificationCenter.default.addObserver(forName: Notification.Name.NSManagedObjectContextObjectsDidChange, object: managedObjectContext, queue: OperationQueue.main) { (notification) in
if self.isViewLoaded {
if let dictionary = notification.userInfo {
print(dictionary[NSInsertedObjectsKey])

if let inserted = dictionary[NSInsertedObjectsKey] as? Set<Location> {
var location = Array(inserted)
}

if let deleted = dictionary[NSDeletedObjectsKey] {
}
}
}
}
}
}

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

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.

Could not cast value of type 'Swift.Optional Swift.AnyObject ' to 'NSFetchRequest'

Add this at the top of your NSManagedObject class definition

//This need to be declared here
@objc(NotificationsItem)

public class NotificationsItem: NSManagedObject, Identifiable {
...

And make sure to set the Codegen of the class to Manual/None

Could not cast value of type '__NSCFData' (0x39490110) to 'NSString' (0x394990ac)

The error is pretty clear: The type of userRefInfo is (NS)Data.

I don't know how userRefInfo is processed further but this is the usual way to get Data from UserDefaults.

if let userRefInfo = userDefaults.data(forKey: SharedPreferenceHelper.USER_REFERER_INFO)
return Mapper<UserRefererInfo>().map(JSONString: userRefInfo)
}

Never value(forKey: and never if foo != nil { ... foo! }

Consider that ObjectMapper became obsolete in favor of Codable in Swift 4+



Related Topics



Leave a reply



Submit