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!
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];
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.
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];
});
精彩评论