Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build An iTunes Search App Requesting Real Data Searching For Artists

Qasa Lee
Qasa Lee
18,915 Points

What about declaring "self" as "unowned self" rather than "weak self" in the closure?(in SearchResultsController.swift)

extension SearchResultsController: UISearchResultsUpdating {
    func updateSearchResults(for searchController: UISearchController) {

        client.searchForArtist(withTerm: searchController.searchBar.text!) { [weak self] (artists, error) in
            self?.dataSource.update(with: artists)
            self?.tableView.reloadData()
        }

    }
}

I suppose that "self"(which is "SearchResultsController") doesn't have a shorter lifetime than its property "client', does that make sense to make it "unowned self" in this closure?

1 Answer

Everton Carneiro
Everton Carneiro
15,994 Points

I've just found a great article on this subject in this link.

As I understand, setting self to unowned is unsafe because you can crash the app if self is no longer in memory. It is like when you force unwrap a value and you find nil on runtime.

Qasa Lee
Qasa Lee
18,915 Points

"Only capture variables as unowned when you can be sure they will be in memory whenever the closure is run, not just because you don’t want to work with an optional self." as it says! Thanks!