When to use a reference type?

A great time to use a reference type is when you are subclassing a built-in class, such as UIViewController. In these cases, there is no point in fighting the system because that would definitely do more harm than good. Another time to use a reference type is when you are creating your own delegate protocols.

Delegates are best implemented as weak reference types. This means that the object that acts as a delegate is referenced weakly by an object to avoid memory leaks. Because value types are passed around by making copies, it does not make sense to have a weak reference to them. In this case, your only choice is to use a reference type.

You can read more about memory leaks and reference cycles in Chapter 24Discovering Bottlenecks with Instruments.

You also need a reference type if it doesn't make sense to pass around copies or something. If you think back to the example of driving to somebody's house, it makes a lot more sense to pass around the address of a house than to give everybody full copies of the house. You might consider the house as having an identity. This means that each house is unique, there is only one house with that exact address and making copies of it makes no sense. If you are working with an object where copying it makes no sense, you likely want to implement it as a reference type, so everybody that receives an instance of that type is looking at the same instance.

One last reason to choose a reference type is if it can save you a lot of typing by subclassing. A lot of people consider subclassing bad, and you can often avoid it, but sometimes it just makes a lot more sense to work with a class hierarchy. The downside is that a lot of subclassing can lead to muddy classes that contain functionality to save typing on a couple of subclasses even though the functionality is not relevant to all subclasses. But just like many tools, subclassing can be quite convenient when used correctly; it's not inherently bad to use it.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset