Swift Core Data From Scratch: Workshop 5

This is the final workshop in the Swift Core Data From Scratch tutorial. You will implement these tasks in the iOS project you worked on last week:

  • Search the database for managed objects that satisfy a condition
  • Display search results in the Books View table view cells

To implement above tasks in the project, you will add code in the BooksViewController class file. Implementing above tasks in the project will be super easy.

Before You Begin

Now, before implementing above tasks in the project, I want you to use the Source Control menu to create a new branch called, “find-managed-objects” from the delete-managed-object branch. In Interface Builder, make sure the Search Bar’s searchBar IBOutlet property is connected. Also, make sure its delegate outlet is connected as well. Why? because you’ll be implement delegate functions of the UISearchBarDelegate protocol in the BooksViewController.swift file.

scdfs-figure5-1

The Search Bar Code

In order to implement above tasks in the project, add these functions of the UISearchBarDelegate protocol in the BooksViewController.swift file:

func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
    searchBar.setShowsCancelButton(true, animated: true)

    if !searchText.isEmpty {
        // Clear out the fetchedResultController
        fetchedResultsController = nil

        // Setup the fetch request
        let fetchRequest = NSFetchRequest(entityName: "Book")

        fetchRequest.fetchLimit = 25
        fetchRequest.predicate = NSPredicate(format: "bookTitle contains[cd] %@", searchText)

        let sortDescriptor = NSSortDescriptor(key: "bookTitle", ascending: true)
        fetchRequest.sortDescriptors = [sortDescriptor]

        // Pass the fetchRequest and the context as parameters to the fetchedResultController
        fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext:context,
            sectionNameKeyPath: nil, cacheName: nil)

        // Make the fetchedResultController a delegate of the MoviesViewController class
        fetchedResultsController.delegate = self

        // Execute the fetch request or display an error message in the Debugger console
        var error: NSError? = nil
        if (!fetchedResultsController.performFetch(&error)) {
            println("Error: \(error?.localizedDescription)")
        }

        // Refresh the table view to show search results
        tableView.reloadData()
    }
}

func searchBarCancelButtonClicked(searchBar: UISearchBar!) {
    searchBar.text = nil
    searchBar.showsCancelButton = false // Hide the cancel
    searchBar.resignFirstResponder() // Hide the keyboard
    fetchManagedObjects()

    // Refresh the table view to show fetchedResultController results
    tableView.reloadData()
}

That’s pretty much all the code you have to add in the file to make the Books View’s Search Bar and its Cancel button work. Now is a good time to use the Source Control menu to commit changes you’ve made to the project, in the git repository.

The first function, textDidChange() is a delegate of the UISearchBarDelegate protocol. Its job is to clear out the fetchedResultsController object variable, dump search results that match the search condition you setup in the predicate statement, and refresh the table view so search results appear in the view’s table view cells, instead of results returned by the fetchManagedObjects() function.

The second function, searchBarCancelButtonClicked() is also a delegate of the UISearchBarDelegate protocol. Its job is pretty obvious-cancel the search session and return the table view back to default mode.

Test The Search Bar Code

All you have to do now is run the app in the iPhone 5s Simulator and test the Search Bar code. As you enter text in the Search Bar’s text field, notice how search result or results are automatically displayed in the Book View’s table view cells. To tell the app that you’re done searching, just click the Cancel button. This action cause the searchBarCancelButtonClicked() function to fired.

scdfs-figure5-2 scdfs-figure5-3

You’ve reached the end of the Swift Core Data From Scratch tutorial. You learned how to use the Swift Programming Language, the NSFetchResultsController class, and the Core Data frame work to implement various Core Data tasks in an iOS application. I hope you had fun and comments are welcomed! 🙂

  • User!

    Hello! Thanks for the amazing tutorial! Does it works on the Xcode 7? Are you tested this codes in the final version of Xcode? I have a problem with implementing UISearchController & UISearchBar in Swift’s Core Data ( NSFetchedResultsController ) Good luck!

    Thanks again!

  • Hey Ismael Idrissie thank you for your comment.

    Now, to fix the problem of loading more than 25 books in the tableView; remove this statement from the BookksViewController.swift file’s fetchManagedObjects() function:

    fetchRequest.fetchLimit = 25

  • Ismael Idrissi

    thanks for all your code
    my only problem is my list of “books” doesn’t show more than 25 books
    if i scroll down it doesn’t load the rest , but the search works