0

Most iPhone code examples use the nonatmoc attribute in their properties. Even those that involve [NSThread detachNewThreadSelector:....]. However, is this really an issue if you are not accessing those properties on the separate thread?

If that is the case, how can you be sure nonatomic properties won't be accessed on this different in the future, at which point you may forget those properties are set as nonatomic. This can create difficult bugs.

Besides setting all properties to atomic, which can be impractical in a large app and may introduce new bugs, what is the best approach in this case?

Please note these these questions are specifically for iOS and not Mac in general.

4thSpace
  • 41,122
  • 88
  • 267
  • 450

1 Answers1

1

First,know that atomicity by itself does not insure thread safety for your class, it simply generates accessors that will set and get your properties in a thread safe way. This is a subtle distinction. To create thread safe code, you will very likely need to do much more than simply use atomic accessors.

Second, another key point to know is that your accessors can be called from background or foreground threads safely regardless of atomicity. The key here is that they must never be called from two threads simultaneously. Nor can you call the setter from one thread while simultaneously calling the getter from another, etc. How you prevent that simultaneous access depends on what tools you use.

That said, to answer your question, you can't know for sure that your accessors won't be accessed on another thread in the future. This is why thread safety is hard, and a lot of code isn't thread safe. In general, if youre making a framework or library, yeah, you can try to make your code thread safe for the purposes of "defensive programming", or you can leave it non-thread safe. The atomicity of your properties is only a small part of that. Whichever you choose, though, be sure to document it so users of your library don't have to wonder.

Jiva DeVoe
  • 1,308
  • 1
  • 9
  • 10
  • Thanks. In regards to your first sentence, can you elaborate on the difference between "thread safety" and "thread safe way"? – 4thSpace Apr 13 '11 at 14:15
  • Here's an excellent discussion of that exact topic: [Atomic vs nonatomic properties](http://stackoverflow.com/questions/588866/atomic-vs-nonatomic-properties/589392#589392) that explains it better than I could. The point here is that, basically an atomic setter/getter prevents the setter or getter from returning an incomplete result, but it does not prevent you from attempting to set a value while getting it, or other various multithreading bugs. To prevent those, look at @synchronize, NSLock, and so on. – Jiva DeVoe Apr 13 '11 at 21:20