Unowned references

Unowned references behave exactly like weak ones: they don’t increase the object’s reference count. However, unlike weak references, they always have a certain value — you can’t declare them as optionals, since they are _never- nil.

To extend the previous example a bit, it would be nice to also know who wrote a certain tutorial. Modify the Tutorial class as shown below:

class Tutorial {

let author: Author

init(title: String, category: String, author: Author, date: Date) { self.author = author

// original code

}

// original code

}

Add the following Author class as well:

class Author {

let name: String let email: String

var tutorial: Tutorial?

init(name: String, email: String) { self.name = name

self.email = email

}

deinit {

print("Goodbye (name)!")

}

}

Each author has a name, an email where you can reach her and an assigned tutorial. The tutorial property is optional because you will set its value after you create the author object with the class designated initializer. You use string interpolation to show the author’s name in the deinit method.

There is still an error in your code however. The previously created tutorial doesn’t yet have an author, so modify its declaration as follows:

var author: Author? = Author(name: "Cosmin", email:

"[email protected]")

var tutorial: Tutorial? = Tutorial(title: "Memory management", category: "Swift", author: author!, date: Date())

Note: You define the tutorial’s author as an optional because you will set it to

nil.

Start the writing process by linking the two together. Add the following line of code where you linked the editor with the tutorial:

author?.tutorial = tutorial

Once you finish writing, you need to send the tutorial to the editing phase. Add the code below at the spot where you set the tutorial and editor to nil:

author = nil

None of the class deinitializers prints anything to the console. You’ve just created another reference cycle, this time between the tutorial and its corresponding author.

Each tutorial on the website has an author — there are no anonymous authors here! The tutorial’s author property is the perfect match for an unowned reference since it’s never nil. Change the property’s declaration in the Tutorial class to the following:

class Tutorial {

unowned let author: Author

// original code

}

You break the reference cycle with the unowned keyword and all the deinit methods run and print the following output to the console now:

Goodbye Cosmin!

Goodbye Memory management! Goodbye Ray!

That’s it for reference cycles for classes. Time to move on to reference cycles with closures.

results matching ""

    No results matching ""