Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

iOS Build a Diary App Using Core Data Understanding Core Data Typical Core Data Stack

Singleton question

After watching Ash Furrow's "Typical Core Data Stack" video, he explained singleton's to us. In his code he used dispatch_once like

static THCoreDataStack *defaultStack;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    defaultStack = [[self alloc] init];
});

return defaultStack;

I learned by initializing it first as nil and then checking if it exists like...

static THCoreDataStack *defaultStack = nil;
if (!defaultStack) {
    defaultStack = [[self alloc] init];
}

return defaultStack;

I'm pretty sure they do the same thing. Does it matter? Is there a difference? Either way, I learned about dispatch_once so thats good. Thanks for any info, always curious. Thanks!

2 Answers

Stone Preston
Stone Preston
42,016 Points

This post from stack overflow states that its approximately 2x faster and semantically cleaner to use dispatch once than if you did the typical nil check way. Its an explicit way of saying "hey, this is only going to happen once"

Great! Thanks for that info and I apologize for asking a question that I now realize that I could have easily googled. Been cramming a little too much I guess. Thanks man.