Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

iOS Introduction to Core Data with Swift 2 Fetching Data Using Fetch Requests Performing a Fetch Request

luke jones
luke jones
8,915 Points

NSFetchRequest Swift 3 Syntax

Trying to create a fetch request with swift 3 (Swift 2 show in video):

 lazy var fetchRequest: NSFetchRequest<Item> = { 
    let request = NSFetchRequest<Item>(entityName: Item.identifier)
    let sortDescriptor = NSSortDescriptor(key: "text", ascending: true)
    request.sortDescriptors = [sortDescriptor]
    return request
}()

Although can't seem to get it to work. In view did load:

    do {
        items = try managedObjectContext.execute(fetchRequest) as! Item
    } catch let error as NSError {
        print("Error fetching Item objects: \(error.localizedDescription), \(error.userInfo)")
    }

which displays a warning stating that cast from 'NSPersistentStoreResult' to unrelated type '[Item]' always fails therefore crashing the app.

1 Answer

Dennis Parussini
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Dennis Parussini
Treehouse Project Reviewer

There's a slightly different method used in Swift 3. You need to use the fetch() method to perform the fetching now.

items = try managedObjectContext.fetch(fetchRequest)

The rest works as usual.

Actually there's a completely new way of doing things in Swift 3. Instead of writing all this

lazy var fetchRequest: NSFetchRequest<Item> = {
        let request = NSFetchRequest<Item>(entityName: Item.identifier)
        let sortDescriptor = NSSortDescriptor(key: "text", ascending: true)
        request.sortDescriptors = [sortDescriptor]
        return request
    }()

you can now create an NSFetchRequest with

let request: NSFetchRequest<Item> = Item.fetchRequest()

Well, you are right but is good to know how to make the request manually.