SimplyKiwi
SimplyKiwi

Reputation: 12444

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!

Upvotes: 4

Views: 10989

Answers (3)

malex
malex

Reputation: 10096

The thread safe common way to initialize some instance using GCD is as follows:

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

Upvotes: 1

tsnorri
tsnorri

Reputation: 2097

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.

Upvotes: 2

Yann Ramin
Yann Ramin

Reputation: 33177

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];

Upvotes: 10

Related Questions