Search code examples
iosswift3magicalrecord

Swift 3 Cast from [NSManagedObject] to unrelated type LeadSource always fails


That warning is being thrown for this line:

LeadSource.mr_findAll(in: localContext).flatMap({$0 as? LeadSource}).forEach({$0.MR_deleteEntityInContext(localContext)})

So the LeadSource class is a subclass of _LeadSource which is a subclass of NSManagedObject, which means that I should be able to cast it to a LeadSource. the mr_findAll function is located in the NSManagedObject+MagicalFinders.h file, which is an extension of NSManagedObject, which means that it recognizes the LeadSource as a NSManagedObject in the first place. Why is this warning being thrown?

LeadSource.h
@interface LeadSource : _LeadSource

_LeadSource.h
@interface _LeadSource : NSManagedObject

mr_findAll returns a NSManagedObject, and LeadSource is a subclass of NSManagedObject, so why does it say the cast fails?


Solution

  • From the comments:

    "The second crucial information besides the classes is that a cast from an array to a non-array always fails."

    Changing my code to ...{$0 as? [LeadSource]}... fixed my issue, notice the brackets around LeadSource casting it to an array.