Avoiding an Objective-C Pitfall #1

Below is a very commonly used design pattern in Objective-C.

CommonDesignPattern

It’s the typical Objective-C “Singleton Pattern” because it does just that.  Returns a singleton of the class it belongs to.  If we take a look at an example that uses it we can see it in action.

Screen Shot 2017-05-16 at 1.07.57 PM

The “@synchronized(self)” statement ensures that only one thread at a time enters that inner block and keeps more than one copy of the class from being created.  Without it two or more threads might just happen to get past the “if(_inst == nil)” statement before one of the threads manages to complete the assignment to the static local variable “_inst”.

If you run this program you get the output you’d expect:

Screen Shot 2017-05-16 at 1.22.27 PM

The class “Test1” created exactly ONE instance of itself, stored it in the static local variable “_inst” and then returned it.  If the program had called the class method a second time it would have gotten the exact same instance that was created in the first call like so:

Screen Shot 2017-05-16 at 1.28.55 PMScreen Shot 2017-05-16 at 1.29.08 PM

All well and good!  Now, let’s add a little wrinkle to the situation by creating a subclass of “Test1”:

Screen Shot 2017-05-16 at 1.08.34 PM

In this example, “Test2” inherits directly from “Test1”.  It’s very simple and doesn’t even override any methods.  We’ve also set the second instance object in the main function, “o2”, to get the result of calling [Test2 instance] instead of [Test1 instance].  But since we didn’t override anything it’s still really calling the same method found in “Test1”.  Now, let’s run it and see what output we get.

Screen Shot 2017-05-16 at 1.41.44 PM

Now, for some of you, this is not what you were expecting to see.  You were probably expecting to see “Returned Class 2 = Test2“.  However the more I thought about it this was exactly what I was expecting to see.  The reason for this is simple.  Static local variables are scoped to the method in which they are created.  Since this was a class method (belongs to the class definition rather than instances of the class) it belongs to the class in which the method was defined.  Bottom line this would have been EXACTLY as if I had coded it as follows:

Screen Shot 2017-05-16 at 3.19.15 PM

Notice that the static local variable is now your everyday, garden variety global variable.  The only difference now is that from a scope perspective it can be “seen” from the entire program instead of just inside the [Test1 instance] method.

Coincidentally, if you reverse the two calls to the “instance” method you’ll get instances of “Test2” instead of “Test1”.

Screen Shot 2017-05-16 at 3.45.09 PMScreen Shot 2017-05-16 at 3.45.22 PM

Why didn’t an instance of “Test1” get created?  Because we called [Test2 instance] instead of [Test1 instance].  But why since we didn’t override that method in “Test2?”  For a better explanation of meta-classes in Objective-C I refer you to this excellent blog post: What is a meta-class in Objective-C?

But there’s also another more problematic issue with this test case.  That “@synchronized(self)” statement?  It’s rendered completely useless in our example if [Test1 instance] is called from one thread and [Test2 instance] is called at the same time from another thread.  The reason is evident in the second line of the output.  Even though the method belongs to the class definition for “Test1” we’re calling it from the scope of the subclass definition “Test2”.  (Again, read the blog post at the link given above.) So if there are two threads and one thread calls [Test1 instance] and the other thread calls [Test2 instance] that synchronization lock will be locking on two entirely different objects because the “self” properties in both calls will be pointing to two different objects.  Bottom line:  you could end up with an instance of the wrong class than what you were expecting.

Below is one solution albeit not the optimal one.  We simply override the class method in “Test2.”

Screen Shot 2017-05-16 at 1.59.34 PMScreen Shot 2017-05-16 at 2.09.22 PM

Why isn’t this the optimal solution?  Because you have blatant code duplication.  Not just within the program as a whole but even worse, given that we’re talking about Object Oriented Programming, within the a subclass!

No, a better solution is needed.  And one that I’ve come up with in my own code is only slightly more complicated but, I think, solves the problem very nicely without adding much memory or CPU time overhead.  Let’s look at the newly refactored “instance” method.

Screen Shot 2017-05-16 at 4.16.12 PM

We will now store the singleton instances in a dictionary using the class name as the key. This ensures that if we call this method using [Test2 instance] we get an actual instance of “Test2” and if we call it using [Test1 instance] we get an actual instance of “Test1”.  Moreover we still only create just one instance of any given class.

Finally we change the object being synchronized on to simply the static base class, [Test1 class], rather than allowing it to be based on the “self” property.

So, after a quick change to the “main” function to test the results.

Screen Shot 2017-05-16 at 4.24.04 PMScreen Shot 2017-05-16 at 4.24.30 PM

And you can now see that the results are more inline with what you would expect without having to duplicate code in the subclasses.

 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s