Cocoa Threading

Everyone has their own vision of how things should work. As you gain more experience in your craft, you become more grizzled. Well learned. After some time, you earn the privledge of passing this experinece on. Oscar Wilde said it best:

Experience is simply the name we give our mistakes.

Multi-threading in software engineering has been around for a long time. Many mistakes have been made, thankfully. From those mistakes, experience was born. Most of the engineering books talk about the essentials, and the dangers that must be respected and adhered to. But while they talk about the pitfalls of what could happen, none of them really give you great guidelines. I’ve been doing this a long time and I’ve worked with people who should not have made some of the mistakes I’ve witnessed.

Are they bad engineers?

Was there a fundamental misunderstanding about multi-threading?

But there are some fantastic guidelines that aren’t well-established. It seems like Brent Simmons and I agree on a lot of the same principles. He’s written a great blog post about Cocoa Threading that every Cocoa developer should read and understand. He refers to his post as his, “barely-organized thoughts on threading and Cocoa applications” but it covers the points in a concise manner.

Thread Communication Exclusively on the Main Thread

First up is his philosophy on all communication between threads taking place on the main thread. He extends this to notifications as well. I’ll add one more to that list which is KVO notifications. This is essential because UIKit and Core Data don’t like operating on secondary threads. I don’t know how many times I’ve seen

NSAssert( [NSThread isMainThread], @"This needs to run in the main thread" );

 go off because I received a notification or call from a secondary thread.

Communication between systems always happens on the main thread. (A system is one or more objects that work together.) In most cases, communication between objects in the same system happens on the main thread too.

If an object does something in the background, that is that object’s business and nobody else’s.

This extends to notifications: from background threads, I always make sure notifications get posted on the main thread. This way every notification observer can always assume that it’s getting called on the main thread.

Regarding KVO, Brent has this to say:

KVO is a trickier thing. Here’s how I handle that: anything happening in a background thread is not observable (by convention). Whatever is going on is private. When it’s time to set public stuff, stuff that could be observed, those things are set on the main thread.

Threading Methods

There’s almost as many different ways to spin off a thread as there are people in the United States. Brent and I also agree on which methods we use:

I’m very deliberate about my threading. I like Grand Central Dispatch, but for my purposes NSOperationQueue works best. The formal, easily-monitored approach of NSOperationQueue works best here. I definitely recommend against anything but GCD and NSOperationQueue — anything else (NSThread’s detach method, etc.) is too random. (Yes, we used it for years, but we have better stuff now.) (In fact, I almost never even use NSInvocationOperation — I much prefer the structure and defined stop/start of NSOperation.)

I use an NSOperation subclass that takes a target and selector in its init method. When it’s finished, it calls the target and selector on the main thread. This way the caller only ever sees the main thread — it creates the operation on the main thread, then gets called back on the main thread. The fact that the operation happens in the background is unknown to the caller: the caller just knows that it’s async, and doesn’t know anything else.

I almost exclusively use NSOperation subclasses with NSOperationQueue in my applications for the same reasons that Brent outlines. You can create multiple NSOperationQueue’s if you need different operating parameters (for example, one queue that is sequential, another queue that can operate concurrently). Making dependencies between various NSOperation’s is as simple as making an addDependency call. Plus, they can have dependencies across different NSOperationQueue’s.


NSCache seems to have suffered from poor marketing. It’s a little gem that very few people seem to know about. I’ll bet most of you have written your own class that performs much of the same functionality. I’ll take the very-well tested and used NSCache, which is also thread-safe, any day.

Locking sucks. If you have to do it, you have to do it. It doesn’t mean you’ve failed — failure would be not-locking when you really do need a lock.

There are a couple other things you can do which make sense.

  1. Use performSelectorOnMainThread to set some data that would otherwise require locking. (This is not a trick to use willy-nilly, though — typically it comes at the very end of an operation, not sprinkled throughout.)
  2. Use NSCache — it’s thread-safe.

I highly recommend you read Brent’s full article, “Some Notes on Threading” over at his site.

About the author

Terry Blanchard

I'm the Vice President of Engineering at Readdle, ex-Apple, design evangelist, drummer, and gadget junkie extraordinaire.

One thought on “Cocoa Threading”

  1. Free Sex Meet With Local Women:

    Popular tags: best lines for dating, bay city dating mi, best app to hook up with someone, bambi dating future, uhh yeah dude dating, fishoutofwater dating site, three prong toggle switch hook up, dating for short guys, uofa connections dating, how many months of dating before saying i love you, how to break the ice on a dating site, michael cassidy dating history, harry reis online dating, 100 free asian dating sites no credit card needed, writing your dating profile examples, uk singles dating free, christian dating website south africa, amoory free dating site, celebrity dating normal person, free rich gay dating site, ohac dating, security dating arrangement, monster dating site, biggest dating sites, american guy dating australian girl, russian dating in pattaya, matchmaking services rochester ny, the perfect male online dating profile, should i go on the same dating site as my ex, tattoo dating website uk, dating text etiquette, korean dating advice, scandinavian dating sites, gay dating site los angeles, best dating apps android india, top asian dating websites, speed dating jersey, exclusive matchmaking london, dating online without membership, dating site san francisco, free navy dating sites, casual dating two guys, dating etiquette in your 50s, si’s dating tips, free online dating fish, classifieds online dating, sugar mama dating site for free, nashville casual hook up, lohana speed dating, free dating in dar es salaam, gay dating memes, why online dating works, speed dating 50 ans montreal, sugar daddy dating uk free, hampton bay ceiling fan hook up, drunk hookup stories, erfahrungsberichte dating portale, dating agency for sale uk, dating articles 2016, dating websites you can browse, free online social dating sites, dating dinner parties melbourne, mature dating west sussex, can radiocarbon dating be used to determine the age of dinosaur fossils explain, free dating in chesterfield, dating sites in mombasa, dating fish of plenty, good internet dating photos, free dating site in armenia, rules for dating a minor in arizona, neighbours co stars dating, dating stock transfer forms, vintage motorcycle club dating certificate, some tips for dating, meet me dating websites, actors dating other actors, dating app autoliker, dating in auckland new zealand, dating ithaca 37, what is the legal age difference for dating in texas, dating oslo norway, christian missionary dating site, my ex wife is dating a black guy, completely free gay dating uk, free online dating wichita ks, assassin’s creed 4 multiplayer matchmaking, dating someone with a baby on the way, senior dating sites perth, instagram new dating app, dating headline samples, france online dating sites, dating site for fitness enthusiasts, legal dating age in colorado, adult dating site free, online dating in kentucky, christian dating websites in usa, dating sites 40 and over, 22 dating 26 year old, kelly clarkson i do not hook up lyrics youtube, one out of 100 chinese dating show, 1d dating, dating a not so attractive guy, dating a cancer woman zodiac sign, dating white girl indian, chattanooga speed dating events, how can i start dating my ex again, phish fan dating site, manga matchmaking, free online dating in canada, egyptian dating apps, how to pick a dating site username, uk dating site online, cancer survivor dating site, good taglines for dating sites examples, cancun dating service, free datehookup dating site, dating seite studenten, wellington dating online, if you read this we re dating now, best dating sites australia free, awkward cast dating, top 3 dating sites in australia, trusted international dating sites, dating websites success stories, search partner dating site, online dating website prices, black and white dating tumblr, dating in high school story, viking fm dating search, casual hookup definition, orlando dating classifieds, charlotte dating websites, top five dating sites, dating online in northern ireland, 40 days dating end, best rated online dating services, dating website millionaires, free dating sites southampton, free online divorce dating site, will destiny raids have matchmaking, found husband on dating site, i want online dating, wilmington nc dating, lgd.xiao8 on chinese dating show with english subtitles, british pakistani dating sites, how to write a great dating email daily mail, speed dating for young professionals in london, examples of great online dating profiles for women, online dating mornington peninsula, japan dating sites, ts hook up apps, natural hair dating website, perks of dating me guy, how long before dating becomes a relationship, who is dodger in hollyoaks dating in real life, dating site funny stories, albury dating site, what do you mean by dating scan, dating age limit in texas, chat dating online free, asperger’s syndrome dating sites, what to text a guy after a hookup, speed dating in rochester mn, christian dating service free, searching for dating site, non alcoholic dating site, free dating site cleveland, how to tell if a hookup likes you, dating sites for educated singles, dating website rape, cape town dating website, chinese speed dating melbourne, signs she’s not worth dating, 100 free dating site like tagged, internet dating killings, mcadams rachel dating, dating passive aggressive woman, radioactive dating potassium 40, njyp speed dating, interracial dating bahamas, dating email sample, dating for 6 weeks, dating sites free mobile, first message on dating websites, what is the dating scene like in dc, dating toronto tumblr, widowers dating site ireland, carbon dating joke, married dating sites northern ireland, free online dating mobile, headline for dating site female, uk popular dating apps, besten dating apps android, equestrian dating canada, eoin macken dating history, dating sites uk 16+, fairy tail dating games, dating after ptsd, grapevine dating london, dating sites tamil, interesting dating websites, hook up ice maker to sink, dating tips what happens after first date, speed dating in newcastle nsw, online dating site rankings, one time dating site, speed dating murcia, fifty plus online dating, gay dating height difference, half plus 7 dating rule, #1 gay dating app, dating monologues, dating service new york, free online dating sites dallas tx, hook up hose to kitchen faucet, speed dating in fairfax va, dating tips for disabled, yahoo hookup site, pakistan dating service, best dating site for older professionals, seniors dating uk, nsa hookup ticket, halo reach firefight matchmaking solo, hook up maya lyrics, steel matchmaking, epilepsy dating site, dating a russian girl advice, guyanese american dating, ff dating my ex part 2, joseline dating history, electronic dating sites, shaone morrisonn dating, best free dating websites 2015, g dragon and cl dating 2011, dating services new zealand, the sims 3 dating service, janelle and val dating 2015, hook up tips, recommended dating sites ireland, what type of girl are you dating, dating voor hoger opgeleiden, dating marine officer, british dating agency, best hookup bars in los angeles, dating ideas in greenville sc, tattoo dating canada, we met on a dating site, banning dating site, dating app for rich guys, best cougar dating websites, best dating profile written by a non-murderer, free dating sites for autism, jessica’s guide to dating on the dark side download free

Leave a Reply

Your email address will not be published. Required fields are marked *