Search code examples
iosswiftcore-dataswift3nsfetchrequest

Swift 3. NSFetchRequest propertiesToFetch


In Swift 3 when we use NSFetchRequest, we have to specify NSFetchRequestResult. But how to get an array of properties values? If I use something like this

let fetchRequest = NSFetchRequest<MyClass>(entityName: "MyClass")
fetchRequest.propertiesToFetch = ["myAttributeName"]

an exception fires when I try to execute fetch request. error: -executeRequest: encountered exception = The database appears corrupt. If I remove a line with propertiesToFetch I don't get any errors, but I get an array of objects, not properties.


Solution

  • I forgot to set resultType for NSFetchRequest.

    let fetchRequest = NSFetchRequest<MyClass>(entityName: "MyClass")
    fetchRequest.propertiesToFetch = ["myAttributeName"]
    fetchRequest.resultType = .dictionaryResultType