Enforcing copy semantics for users of my Objective-C class

92 Views Asked by At

I have an Objective-C class that's intended for copy semantics.

 @property (copy) ViewState* viewState;

It’s not immutable, but everything that hangs on to a ViewState instance needs its own distinct copy. In fact, if some other class mistakenly tries

 @property (strong) ViewState* viewState;

we'll eventually crash.

How do we enforce or encourage client classes to use the correct semantics?

In C++, for example, we could prohibit assignment

 private:
 CPViewState* operator=(const CPViewState*) const;  // no implementation

But we can't do that in Objective-C. For the opposite case, where we want to prohibit copying, we can log an error or throw an exception from copyWithZone:.

How can I either require copy semantics or, at least, make it clear to future developers that they want to use copy semantics?

1

There are 1 best solutions below

0
On

Copy semantics cannot be enforced from within the class itself, as you correctly explained.

Depending on where and how ViewState objects are created, and what that means conceptually, there are different things that could work.

I am not sure about what ViewState means in your project, but if it makes sense you could supply a singleton/factory ViewStateFactory class, which would have a few methods for creating and/or copying ViewState objects that clients would use. ViewStateFactory could then ensure that new copies are supplied every time a client requests a ViewState object.

Note that this is adds some boilerplate to the clients of your class. It also doesn't prevent people from going behind ViewStateFactory and directly allocating and/or referencing ViewState objects. But it could make more clear your intentions and how you want other people to use your class.