开发者

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!


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];
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜