What is the difference between writing
+(MyObj*)obj
{
static MyObj *obj= nil;
if(!obj)
obj = [[super allocWithZone:nil] nil];
}
and
+(MyObj*)obj
{
MyObj *obj= nil;
if(!obj)
obj = [[super allocWithZone:nil] nil];
}
The storage is static, which means there will be only one variable per process e.g. only one variable throughout iOS application.
For example, once you assign something to static variable, the value will be there even after ending of the function. This is not the case when using local variable, which the value assigned to the variable will disappear after ending of the scope e.g. function.
From the second example, the obj in second one will always be nil at the beginning of the function because it is declared as local variable. On the other hand, obj in the first one will be nil at first call only because it will get assigned to new instance of MyObj after first call.
With the first method: Calling [WhateverClass obj] and then subsequently calling [WhateverClass obj] again will return the exact same instance of MyObj.
This is because on the first [WhateverClass obj] call the static *obj is set to nil. The if statement is invoked and *obj now points to the newly initalized instance. On the subsequent calls static *obj still points to the object from the first call (i.e. it persists between calls, and the static MyObj *obj = nil is not run). For this reason, you need to be careful with statics. Under ARC (Automatic Reference Counting) unless *obj is set back to nil again sometime in the future this object will continue to exist in memory until the process terminates.
With the second method: [WhateverClass obj] and [WhateverClass obj] will return a new instance of MyObj each time. This scope is called automatic and the default behaviour is that once you exit the scope (a set of curly braces) all variables defined in the braces are lost.
For further reading http://nshipster.com/c-storage-classes/ gives a pretty good overview.