views:

6668

answers:

7

What does "nonatomic" mean in this code?

@property(nonatomic, retain) UITextField *theUsersName;

What is the difference between atomic and nonatomic?

Thanks

+1  A: 

If you specify "atomic", the generated access functions have some extra code to guard against simultaneous updates.

Paul Tomblin
+2  A: 

Usually atomic means that writes/reads to the property happen as a single operation. http://en.wikipedia.org/wiki/Atomic_operation

Cipher
+2  A: 

In a multi-threaded program, an atomic operation cannot be interrupted partially through, whereas nonatomic operations can.

Therefore, you should use mutexes (or something like that) if you have a critical operation that is nonatomic that you don't want interrupted.

joshdick
+27  A: 

Take a look at the Apple Docs.

Basically, if you say nonatomic, and you generate the accessors using @synthesize, then if multiple threads try to change/read the property at once, badness can happen. You can get partially-written values or over-released/retained objects, which can easily lead to crashes. (This is potentially a lot faster than an atomic accessor, though.)

If you use the default (which is atomic), then the @synthesized methods use an object-level lock to ensure that multiple reads/writes to a property are serialized. As the Apple docs point out, this doesn't mean the whole object is thread-safe, but the property reads/writes are.

Of course, if you implement your own accessors rather than using @synthesize, I think these declarations do nothing except express your intent as to whether the property is implemented in a threadsafe manner.

Jesse Rusak
Thanks man! Thanks for the help
Daniel Kindler
+2  A: 

In addition to what's already been said about threadsafeness, non-atomic properties are faster than atomic accessors. It's not something you usually need to worry about, but keep it in mind. Core Data generated properties are nonatomic partially for this reason.

Marc Charbonneau
+2  A: 

@paul-tomblin, you can't specify atomic, there is no such keyword. atomic is the default. you can only specify nonatomic to change the default.

Use comments to reply to other answers.
Emil
+2  A: 

One is for multi threads. One isnt