Objective-C Static Variables: Thanks, Apple Docs! [#iosdev #xcode]

I was looking for a very straightforward and concise definition of static variables and how they can be used in Objective-C, since I had already been using them, but only considering their usage in the context of how they are used in other languages (like C# and Java) without really thinking about their purpose and usage in Objective-C.

Thankfully, one needs only look as far as the Apple Developer Library and the official guide for the language (navigate to: Objects, Classes and Messaging > Classes > Class Objects):

The Objective-C Programming Language: Objects, Classes, and Messaging

Declaring a variable static limits its scope to just the class—and to just the part of the class that’s implemented in the file. (Thus unlike instance variables, static variables cannot be inherited by, or directly manipulated by, subclasses.) This pattern is commonly used to define shared instances of a class (such as singletons; see “Creating a Singleton Instance” in Cocoa Fundamentals Guide).

and then a little further down…

Static variables help give the class object more functionality than just that of a factory producing instances; it can approach being a complete and versatile object in its own right. A class object can be used to coordinate the instances it creates, dispense instances from lists of objects already created, or manage other processes essential to the application. In the case when you need only one object of a particular class, you can put all the object’s state into static variables and use only class methods. This saves the step of allocating and initializing an instance.

Sometimes we just do things based on “clipboard inheritance” from examples on Stackoverflow, etc., but once in a while it’s good to actually dive into the reasons why those examples are the way they are, or how they can be changed to suit a different purpose.