Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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.