Check if an object exists - Objective C

Instead of re-creating the object over and over, is there a way to check if the object exists in the if statement?

Thanks!

+4
source share
3 answers

Assuming the reference to the object is nil , if there is no object, you can use

 NSThing *myobj = nil; if (!myobj) myobj = [[NSThing alloc] init]; [myobj message]; 
+9
source

Depends on your situation. You can use a static variable, i.e.

 - (void) doSomething { static id foo = nil; if (! foo) foo = [[MyClass alloc] init]; // Do something with foo. } 

The first time you call -doSomething, MyClass will be created. Please note that this is not thread safe.

Another way is to use singleton. Perhaps the best way is to instantiate the object when the application finishes launching and pass the object to other objects that it may need.

+2
source

A thread-safe general way to initialize an instance using a GCD is as follows:

 static dispatch_once_t once; dispatch_once(&once, ^{ obj = [NSSomeThing new]; }); 
+1
source

All Articles