magicalpanda / MagicalRecord

Super Awesome Easy Fetching for Core Data!
Other
10.8k stars 1.79k forks source link

(Swift) (Select distinct) fatal error: NSArray element failed to match the Swift Array Element type #1311

Open RomainPln opened 6 years ago

RomainPln commented 6 years ago

Hi, I want to find all distinct values of aPropertyName on MyEntity records, I wrote:

        let aRequest = MyEntity.mr_requestAllSorted(by: "aPropertyName", ascending: true)
        aRequest.propertiesToFetch = ["aPropertyName"]
        aRequest.returnsDistinctResults = true
        aRequest.resultType = .dictionaryResultType
        let testResult = MyEntity.mr_executeFetchRequest(aRequest)

As a result I have

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

Whatever I try to do with testResult. Trying to cast testResult does not work and produces the same runtime crash. (A workaround could be to map a classic request result but that's less efficient and elegant)

thomasaw commented 6 years ago

Have you found a solution or workaround for this?

thomasaw commented 6 years ago

My workaround:

extension NSManagedObject {
    // This has the function of MagicalRecord MR_executeFetchRequest, but is compatible with Swift
    static func fetch(_ request: NSFetchRequest<NSFetchRequestResult>) -> [Any]? {
        let context = NSManagedObjectContext.mr_default()
        var categoryObjects: [Any]?
        context.performAndWait() {
            do {
                categoryObjects = try context.fetch(request)
            } catch {
                categoryObjects = nil
            }
        }

        return categoryObjects
    }
}