Reputation: 12444
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
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
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
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