Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if object exists - Objective C

Instead of recreating an object over and over again, is there a way I can check if an object exists in an if statement?

Thanks!

like image 473
SimplyKiwi Avatar asked Dec 17 '22 11:12

SimplyKiwi


2 Answers

Assuming your object reference is set to nil if there is no object, then you can use

NSThing *myobj = nil;

if (!myobj)
    myobj = [[NSThing alloc] init];
[myobj message];
like image 162
Yann Ramin Avatar answered Jan 01 '23 16:01

Yann Ramin


Depends on your situation. You could 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 -doSomething gets called, MyClass will be instantiated. Note that this isn't thread-safe.

Another way is to use a singleton. Possibly a better way is to instantiate the object when the application has finished launching and pass the object to any other objects that might need it.

like image 20
tsnorri Avatar answered Jan 01 '23 15:01

tsnorri