What does the property "Nonatomic" mean? - ios

What does "nonatomic" mean in this code?
#property(nonatomic, retain) UITextField *theUsersName;
What is the difference between atomic and nonatomic?
Thanks

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; there used to be no keyword for this, but there is now), then the #synthesized methods use an object-level lock to ensure that multiple reads/writes to a single property are serialized. As the Apple docs point out, this doesn't mean the whole object is thread-safe, but the individual 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.

After reading so many Articles and StackOverflow posts, and having made demo apps to check Variable property attributes, I decided to put all the attributes information together
atomic //default
nonatomic
strong=retain //default
weak= unsafe_unretained
retain
assign //default
unsafe_unretained
copy
readonly
readwrite //default
so below is the detailed article link where you can find above mentioned all attributes, that will definitely help you.
Many thanks to all the people who give best answers here!!
Variable property attributes or Modifiers in iOS
atomic
Atomic means only one thread access the variable (static type).
Atomic is thread safe.
But it is slow in performance.
Atomic is default behavior.
Atomic accessors in a non garbage-collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value.
it is not actually a keyword.
Example :
#property (retain) NSString *name;
#synthesize name;
nonatomic
Nonatomic means multiple thread access the variable (dynamic type).
Nonatomic is thread unsafe.
But it is fast in performance.
Nonatomic is NOT default behavior; we need to add nonatomic keyword in property attribute.
it may result in unexpected behavior, when two different process (threads) access the same variable at the same time.
Example:
#property (nonatomic, retain) NSString *name;
#synthesize name;

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.

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.

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

Usually atomic means that writes/reads to the property happen as a single operation.
Atomic_operation

You can able to get a handle of this stuffs by reading the below article.
Threading Explained with the nonatomic's purpose
nonatomic - Not Thread Safe
atomic - Thread Safe - This is the default property attribute.

The "atomic” means that access to the property is thread-safe. while the "nonatomic" is the opposite of it.
When you declare a property in Objective-C the property are atomic by default so that synthesized accessors provide robust access to property in a multithreaded environment—that is, the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently. But if you declare property as nonatomic like below
#property (nonatomic, retain) NSString *myString;
then it means a synthesized accessor for an object property simply returns the value directly.
The effect of the nonatomic attribute depends on the environment. By default, synthesized accessors are atomic. So nonatomic is considerably faster than atomic.

One is for multi threads. One isnt

Related

Questions about atomic property in multithread operations, which case should we use atomic? [duplicate]

What do atomic and nonatomic mean in property declarations?
#property(nonatomic, retain) UITextField *userName;
#property(atomic, retain) UITextField *userName;
#property(retain) UITextField *userName;
What is the operational difference between these three?
The last two are identical; "atomic" is the default behavior (note that it is not actually a keyword; it is specified only by the absence of nonatomic -- atomic was added as a keyword in recent versions of llvm/clang).
Assuming that you are #synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory. (Note: #synthesize is now the default behavior in recent versions of LLVM. There is also no need to declare instance variables; they will be synthesized automatically, too, and will have an _ prepended to their name to prevent accidental direct access).
With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.
In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than "atomic".
What "atomic" does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.
Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.
Adding to this:
atomicity of a single property also cannot guarantee thread safety when multiple dependent properties are in play.
Consider:
#property(atomic, copy) NSString *firstName;
#property(atomic, copy) NSString *lastName;
#property(readonly, atomic, copy) NSString *fullName;
In this case, thread A could be renaming the object by calling setFirstName: and then calling setLastName:. In the meantime, thread B may call fullName in between thread A's two calls and will receive the new first name coupled with the old last name.
To address this, you need a transactional model. I.e. some other kind of synchronization and/or exclusion that allows one to exclude access to fullName while the dependent properties are being updated.
This is explained in Apple's documentation, but below are some examples of what is actually happening.
Note that there is no "atomic" keyword, if you do not specify "nonatomic", then the property is atomic, but specifying "atomic" explicitly will result in an error.
If you do not specify "nonatomic", then the property is atomic, but you can still specify "atomic" explicitly in recent versions if you want to.
//#property(nonatomic, retain) UITextField *userName;
//Generates roughly
- (UITextField *) userName {
return userName;
}
- (void) setUserName:(UITextField *)userName_ {
[userName_ retain];
[userName release];
userName = userName_;
}
Now, the atomic variant is a bit more complicated:
//#property(retain) UITextField *userName;
//Generates roughly
- (UITextField *) userName {
UITextField *retval = nil;
#synchronized(self) {
retval = [[userName retain] autorelease];
}
return retval;
}
- (void) setUserName:(UITextField *)userName_ {
#synchronized(self) {
[userName_ retain];
[userName release];
userName = userName_;
}
}
Basically, the atomic version has to take a lock in order to guarantee thread safety, and also is bumping the ref count on the object (and the autorelease count to balance it) so that the object is guaranteed to exist for the caller, otherwise there is a potential race condition if another thread is setting the value, causing the ref count to drop to 0.
There are actually a large number of different variants of how these things work depending on whether the properties are scalar values or objects, and how retain, copy, readonly, nonatomic, etc interact. In general the property synthesizers just know how to do the "right thing" for all combinations.
Atomic
is the default behavior
will ensure the present process is completed by the CPU, before another process accesses the variable
is not fast, as it ensures the process is completed entirely
Non-Atomic
is NOT the default behavior
faster (for synthesized code, that is, for variables created using #property and #synthesize)
not thread-safe
may result in unexpected behavior, when two different process access the same variable at the same time
The best way to understand the difference is using the following example.
Suppose there is an atomic string property called "name", and if you call [self setName:#"A"] from thread A, call [self setName:#"B"] from thread B, and call [self name] from thread C, then all operations on different threads will be performed serially which means if one thread is executing a setter or getter, then other threads will wait.
This makes property "name" read/write safe, but if another thread, D, calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC), but not thread-safe as another threads can simultaneously send any type of messages to the object. The developer should ensure thread-safety for such objects.
If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, either one of A, B or C will execute first, but D can still execute in parallel.
The syntax and semantics are already well-defined by other excellent answers to this question. Because execution and performance are not detailed well, I will add my answer.
What is the functional difference between these 3?
I'd always considered atomic as a default quite curious. At the abstraction level we work at, using atomic properties for a class as a vehicle to achieve 100% thread-safety is a corner case. For truly correct multithreaded programs, intervention by the programmer is almost certainly a requirement. Meanwhile, performance characteristics and execution have not yet been detailed in depth. Having written some heavily multithreaded programs over the years, I had been declaring my properties as nonatomic the entire time because atomic was not sensible for any purpose. During discussion of the details of atomic and nonatomic properties this question, I did some profiling encountered some curious results.
Execution
Ok. The first thing I would like to clear up is that the locking implementation is implementation-defined and abstracted. Louis uses #synchronized(self) in his example -- I have seen this as a common source of confusion. The implementation does not actually use #synchronized(self); it uses object level spin locks. Louis's illustration is good for a high-level illustration using constructs we are all familiar with, but it's important to know it does not use #synchronized(self).
Another difference is that atomic properties will retain/release cycle your objects within the getter.
Performance
Here's the interesting part: Performance using atomic property accesses in uncontested (e.g. single-threaded) cases can be really very fast in some cases. In less than ideal cases, use of atomic accesses can cost more than 20 times the overhead of nonatomic. While the Contested case using 7 threads was 44 times slower for the three-byte struct (2.2 GHz Core i7 Quad Core, x86_64). The three-byte struct is an example of a very slow property.
Interesting side note: User-defined accessors of the three-byte struct were 52 times faster than the synthesized atomic accessors; or 84% the speed of synthesized nonatomic accessors.
Objects in contested cases can also exceed 50 times.
Due to the number of optimizations and variations in implementations, it's quite difficult to measure real-world impacts in these contexts. You might often hear something like "Trust it, unless you profile and find it is a problem". Due to the abstraction level, it's actually quite difficult to measure actual impact. Gleaning actual costs from profiles can be very time consuming, and due to abstractions, quite inaccurate. As well, ARC vs MRC can make a big difference.
So let's step back, not focussing on the implementation of property accesses, we'll include the usual suspects like objc_msgSend, and examine some real-world high-level results for many calls to a NSString getter in uncontested cases (values in seconds):
MRC | nonatomic | manually implemented getters: 2
MRC | nonatomic | synthesized getter: 7
MRC | atomic | synthesized getter: 47
ARC | nonatomic | synthesized getter: 38 (note: ARC's adding ref count cycling here)
ARC | atomic | synthesized getter: 47
As you have probably guessed, reference count activity/cycling is a significant contributor with atomics and under ARC. You would also see greater differences in contested cases.
Although I pay close attention to performance, I still say Semantics First!. Meanwhile, performance is a low priority for many projects. However, knowing execution details and costs of technologies you use certainly doesn't hurt. You should use the right technology for your needs, purposes, and abilities. Hopefully this will save you a few hours of comparisons, and help you make a better informed decision when designing your programs.
Atomic = thread safety
Non-atomic = No thread safety
Thread safety:
Instance variables are thread-safe if they behave correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
In our context:
If a thread changes the value of the instance the changed value is available to all the threads, and only one thread can change the value at a time.
Where to use atomic:
if the instance variable is gonna be accessed in a multithreaded environment.
Implication of atomic:
Not as fast as nonatomic because nonatomic doesn't require any watchdog work on that from runtime .
Where to use nonatomic:
If the instance variable is not gonna be changed by multiple threads you can use it. It improves the performance.
After reading so many articles, Stack Overflow posts and making demo applications to check variable property attributes, I decided to put all the attributes information together:
atomic // Default
nonatomic
strong = retain // Default
weak = unsafe_unretained
retain
assign // Default
unsafe_unretained
copy
readonly
readwrite // Default
In the article Variable property attributes or modifiers in iOS you can find all the above-mentioned attributes, and that will definitely help you.
atomic
atomic means only one thread access the variable (static type).
atomic is thread safe.
But it is slow in performance
atomic is the default behavior
Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value.
It is not actually a keyword.
Example:
#property (retain) NSString *name;
#synthesize name;
nonatomic
nonatomic means multiple thread access the variable (dynamic type).
nonatomic is thread-unsafe.
But it is fast in performance
nonatomic is NOT default behavior. We need to add the nonatomic keyword in the property attribute.
It may result in unexpected behavior, when two different process (threads) access the same variable at the same time.
Example:
#property (nonatomic, retain) NSString *name;
#synthesize name;
I found a pretty well put explanation of atomic and non-atomic properties here. Here's some relevant text from the same:
'atomic' means it cannot be broken down.
In OS/programming terms an atomic function call is one that cannot be interrupted - the entire function must be executed, and not swapped out of the CPU by the OS's usual context switching until it's complete. Just in case you didn't know: since the CPU can only do one thing at a time, the OS rotates access to the CPU to all running processes in little time-slices, to give the illusion of multitasking. The CPU scheduler can (and does) interrupt a process at any point in its execution - even in mid function call. So for actions like updating shared counter variables where two processes could try to update the variable at the same time, they must be executed 'atomically', i.e., each update action has to finish in its entirety before any other process can be swapped onto the CPU.
So I'd be guessing that atomic in this case means the attribute reader methods cannot be interrupted - in effect meaning that the variable(s) being read by the method cannot change their value half way through because some other thread/call/function gets swapped onto the CPU.
Because the atomic variables can not be interrupted, the value contained by them at any point is (thread-lock) guaranteed to be uncorrupted, although, ensuring this thread lock makes access to them slower. non-atomic variables, on the other hand, make no such guarantee but do offer the luxury of quicker access. To sum it up, go with non-atomic when you know your variables won't be accessed by multiple threads simultaneously and speed things up.
Atomic :
Atomic guarantees that access to the property will be performed in an atomic manner. E.g. it always return a fully initialised objects, any get/set of a property on one thread must complete before another can access it.
If you imagine the following function occurring on two threads at once you can see why the results would not be pretty.
-(void) setName:(NSString*)string
{
if (name)
{
[name release];
// what happens if the second thread jumps in now !?
// name may be deleted, but our 'name' variable is still set!
name = nil;
}
...
}
Pros :
Return of fully initialised objects each time makes it best choice in case of multi-threading.
Cons :
Performance hit, makes execution a little slower
Non-Atomic :
Unlike Atomic, it doesn't ensure fully initialised object return each time.
Pros :
Extremely fast execution.
Cons :
Chances of garbage value in case of multi-threading.
Easiest answer first: There's no difference between your second two examples. By default, property accessors are atomic.
Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value.
See the "Performance and Threading" section of Apple's Objective-C 2.0 documentation for some more information and for other considerations when creating multi-threaded apps.
Atomic means only one thread accesses the variable (static type). Atomic is thread-safe, but it is slow.
Nonatomic means multiple threads access the variable (dynamic type). Nonatomic is thread-unsafe, but it is fast.
Atomic is thread safe, it is slow and it well-assures (not guaranteed) that only the locked value is provided no matter how many threads are attempting access over the same zone. When using atomic, a piece of code written inside this function becomes the part of the critical section, to which only one thread can execute at a time.
It only assures the thread safety; it does not guarantee that. What I mean is you hire an expert driver for you car, still it doesn't guarantees car won't meet an accident. However, probability remains the slightest.
Atomic - it can't be broken down, so the result is expected. With nonatomic - when another thread access the memory zone it can modify it, so the result is unexpected.
Code Talk :
Atomic make getter and setter of the property thread safe. for example if u have written :
self.myProperty = value;
is thread safe.
[myArray addObject:#"Abc"]
is NOT thread safe.
atomic (default)
Atomic is the default: if you don’t type anything, your property is
atomic. An atomic property is guaranteed that if you try to read from
it, you will get back a valid value. It does not make any guarantees
about what that value might be, but you will get back good data, not
just junk memory. What this allows you to do is if you have multiple
threads or multiple processes pointing at a single variable, one
thread can read and another thread can write. If they hit at the same
time, the reader thread is guaranteed to get one of the two values:
either before the change or after the change. What atomic does not
give you is any sort of guarantee about which of those values you
might get. Atomic is really commonly confused with being thread-safe,
and that is not correct. You need to guarantee your thread safety
other ways. However, atomic will guarantee that if you try to read,
you get back some kind of value.
nonatomic
On the flip side, non-atomic, as you can probably guess, just means,
“don’t do that atomic stuff.” What you lose is that guarantee that you
always get back something. If you try to read in the middle of a
write, you could get back garbage data. But, on the other hand, you go
a little bit faster. Because atomic properties have to do some magic
to guarantee that you will get back a value, they are a bit slower. If
it is a property that you are accessing a lot, you may want to drop
down to nonatomic to make sure that you are not incurring that speed
penalty.
See more here: https://realm.io/news/tmi-objective-c-property-attributes/
There is no such keyword "atomic"
#property(atomic, retain) UITextField *userName;
We can use the above like
#property(retain) UITextField *userName;
See Stack Overflow question I am getting issues if I use #property(atomic,retain)NSString *myString.
The default is atomic, this means it does cost you performance whenever you use the property, but it is thread safe. What Objective-C does, is set a lock, so only the actual thread may access the variable, as long as the setter/getter is executed.
Example with MRC of a property with an ivar _internal:
[_internal lock]; //lock
id result = [[value retain] autorelease];
[_internal unlock];
return result;
So these last two are the same:
#property(atomic, retain) UITextField *userName;
#property(retain) UITextField *userName; // defaults to atomic
On the other hand does nonatomic add nothing to your code. So it is only thread safe if you code security mechanism yourself.
#property(nonatomic, retain) UITextField *userName;
The keywords doesn't have to be written as first property attribute at all.
Don't forget, this doesn't mean that the property as a whole is thread-safe. Only the method call of the setter/getter is. But if you use a setter and after that a getter at the same time with 2 different threads, it could be broken too!
-Atomic means only one thread access the variable(static type).
-Atomic is thread safe.
-but it is slow in performance
How to declare:
As atomic is default so,
#property (retain) NSString *name;
AND in implementation file
self.name = #"sourov";
Suppose a task related to three properties are
#property (retain) NSString *name;
#property (retain) NSString *A;
#property (retain) NSString *B;
self.name = #"sourov";
All properties work parallelly (like asynchronously).
If you call "name" from thread A,
And
At the same time if you call
[self setName:#"Datta"]
from thread B,
Now If *name property is nonatomic then
It will return value "Datta" for A
It will return value "Datta" for B
Thats why non atomic is called thread unsafe But but it is fast in performance because of parallel execution
Now If *name property is atomic
It will ensure value "Sourov" for A
Then It will return value "Datta" for B
That's why atomic is called thread Safe and
That's why it is called read-write safe
Such situation operation will perform serially.
And Slow in performance
- Nonatomic means multiple thread access the variable(dynamic type).
- Nonatomic is thread unsafe.
- but it is fast in performance
-Nonatomic is NOT default behavior, we need to add nonatomic keyword in property attribute.
For In Swift
Confirming that Swift properties are nonatomic in the ObjC sense. One reason is so you think about whether per-property atomicity is sufficient for your needs.
Reference: https://forums.developer.apple.com/thread/25642
Fro more info please visit the website
http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html
If you are using your property in multi-threaded code then you would be able to see the difference between nonatomic and atomic attributes. Nonatomic is faster than atomic and atomic is thread-safe, not nonatomic.
Vijayendra Tripathi has already given an example for a multi-threaded environment.
Before you begin: You must know that every object in memory needs to be deallocated from memory for a new writer to happen. You can't just simply write on top of something as you do on paper. You must first erase (dealloc) it and then you can write onto it. If at the moment that the erase is done (or half done) and nothing has yet been wrote (or half wrote) and you try to read it could be very problematic! Atomic and nonatomic help you treat this problem in different ways.
First read this question and then read Bbum's answer. In addition, then read my summary.
atomic will ALWAYS guarantee
If two different people want to read and write at the same time, your paper won't just burn! --> Your application will never crash, even in a race condition.
If one person is trying to write and has only written 4 of the 8 letters to write, then no can read in the middle, the reading can only be done when all 8 letters is written --> No read(get) will happen on 'a thread that is still writing', i.e. if there are 8 bytes to bytes to be written, and only 4 bytes are written——up to that moment, you are not allowed to read from it. But since I said it won't crash then it would read from the value of an autoreleased object.
If before writing you have erased that which was previously written on paper and then someone wants to read you can still read. How? You will be reading from something similar to Mac OS Trash bin ( as Trash bin is not still 100% erased...it's in a limbo) ---> If ThreadA is to read while ThreadB has already deallocated to write, you would get a value from either the final fully written value by ThreadB or get something from autorelease pool.
Retain counts are the way in which memory is managed in Objective-C.
When you create an object, it has a retain count of 1. When you send
an object a retain message, its retain count is incremented by 1. When
you send an object a release message, its retain count is decremented
by 1. When you send an object an autorelease message, its retain count
is decremented by 1 at some stage in the future. If an objectʼs retain
count is reduced to 0, it is deallocated.
Atomic doesn't guarantee thread safety, though it's useful for achieving thread safety. Thread Safety is relative to how you write your code/ which thread queue you are reading/writing from. It only guarantees non-crashable multithreading.
What?! Are multithreading and thread safety different?
Yes. Multithreading means: multiple threads can read a shared piece of data at the same time and we will not crash, yet it doesn't guarantee that you aren't reading from a non-autoreleased value. With thread safety, it's guaranteed that what you read is not auto-released.
The reason that we don't make everything atomic by default is, that there is a performance cost and for most things don't really need thread safety. A few parts of our code need it and for those few parts, we need to write our code in a thread-safe way using locks, mutex or synchronization.
nonatomic
Since there is no such thing like Mac OS Trash Bin, then nobody cares whether or not you always get a value (<-- This could potentially lead to a crash), nor anybody cares if someone tries to read halfway through your writing (although halfway writing in memory is very different from halfway writing on paper, on memory it could give you a crazy stupid value from before, while on paper you only see half of what's been written) --> Doesn't guarantee to not crash, because it doesn't use autorelease mechanism.
Doesn't guarantee full written values to be read!
Is faster than atomic
Overall they are different in 2 aspects:
Crashing or not because of having or not having an autorelease pool.
Allowing to be read right in the middle of a 'not yet finished write or empty value' or not allowing and only allowing to read when the value is fully written.
Atomicity
atomic (default)
Atomic is the default: if you don’t type anything, your property is
atomic. An atomic property is guaranteed that if you try to read from
it, you will get back a valid value. It does not make any guarantees
about what that value might be, but you will get back good data, not
just junk memory. What this allows you to do is if you have multiple
threads or multiple processes pointing at a single variable, one
thread can read and another thread can write. If they hit at the same
time, the reader thread is guaranteed to get one of the two values:
either before the change or after the change. What atomic does not
give you is any sort of guarantee about which of those values you
might get. Atomic is really commonly confused with being thread-safe,
and that is not correct. You need to guarantee your thread safety
other ways. However, atomic will guarantee that if you try to read,
you get back some kind of value.
nonatomic
On the flip side, non-atomic, as you can probably guess, just means,
“don’t do that atomic stuff.” What you lose is that guarantee that you
always get back something. If you try to read in the middle of a
write, you could get back garbage data. But, on the other hand, you go
a little bit faster. Because atomic properties have to do some magic
to guarantee that you will get back a value, they are a bit slower. If
it is a property that you are accessing a lot, you may want to drop
down to nonatomic to make sure that you are not incurring that speed
penalty. Access
courtesy https://academy.realm.io/posts/tmi-objective-c-property-attributes/
Atomicity property attributes (atomic and nonatomic) are not reflected in the corresponding Swift property declaration, but the atomicity guarantees of the Objective-C implementation still hold when the imported property is accessed from Swift.
So — if you define an atomic property in Objective-C it will remain atomic when used by Swift.
courtesy
https://medium.com/#YogevSitton/atomic-vs-non-atomic-properties-crash-course-d11c23f4366c
The atomic property ensures to retain a fully initialised value irrespective of how many threads are doing getter & setter on it.
The nonatomic property specifies that synthesized accessors simply set or return a value directly, with no guarantees about what happens if that same value is accessed simultaneously from different threads.
Atomic means only one thread can access the variable at a time (static type). Atomic is thread-safe, but it is slow.
Nonatomic means multiple threads can access the variable at same time (dynamic type). Nonatomic is thread-unsafe, but it is fast.
The truth is that they use spin lock to implement atomic property. The code as below:
static inline void reallySetProperty(id self, SEL _cmd, id newValue,
ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
{
id oldValue;
id *slot = (id*) ((char*)self + offset);
if (copy) {
newValue = [newValue copyWithZone:NULL];
} else if (mutableCopy) {
newValue = [newValue mutableCopyWithZone:NULL];
} else {
if (*slot == newValue) return;
newValue = objc_retain(newValue);
}
if (!atomic) {
oldValue = *slot;
*slot = newValue;
} else {
spin_lock_t *slotlock = &PropertyLocks[GOODHASH(slot)];
_spin_lock(slotlock);
oldValue = *slot;
*slot = newValue;
_spin_unlock(slotlock);
}
objc_release(oldValue);
}
In a single line:
Atomic is thread safe. Nonatomic is thread-unsafe.
If you are using atomic, it means the thread will be safe and read-only. If you are using nonatomic, it means the multiple threads access the variable and is thread unsafe, but it is executed fast, done a read and write operations; this is a dynamic type.
Atomic: Ensure thread-safety by locking the thread using NSLOCK.
Non atomic: Doesn't ensure thread-safety as there is no thread-locking mechanism.
To simplify the entire confusion, let us understand mutex lock.
Mutex lock, as per the name, locks the mutability of the object. So if the object is accessed by a class, no other class can access the same object.
In iOS, #sychronise also provides the mutex lock .Now it serves in FIFO mode and ensures the flow is not affected by two classes sharing the same instance. However, if the task is on main thread, avoid accessing object using atomic properties as it may hold your UI and degrade the performance.
Atomic properties :- When a variable assigned with atomic property that means it has only one thread access and it will be thread safe and will be slow in performance perspective, will have default behaviour.
Non Atomic Properties :- When a variable assigned with nonatomic property that means it has multi thread access and it will not be thread safe and will be fast in performance perspective, will have default behaviour and when two different threads want to access variable at same time it will give unexpected results.

Why properties are always said to be made nonatomic in Objective C? [duplicate]

This question already has answers here:
What's the difference between the atomic and nonatomic attributes?
(27 answers)
Closed 9 years ago.
It is said that nonatomic option will make your setter method run faster. I googled it but am not able to understand. Could someone tell me why?
Declaring a property atomic makes compiler generate additional code that prevents concurrent access to the property. This additional code locks a semaphore, then gets or sets the property, and then unlock the semaphore. Compared to setting or getting a primitive value or a pointer, locking and unlocking a semaphore is expensive (although it is usually negligible if you consider the overall flow of your app).
Since most of your classes under iOS, especially the ones related to UI, will be used in a single-threaded environment, it is safe to drop atomic (i.e. write nonatomic, because properties are atomic by default): even though the operation is relatively inexpensive, you do not want to pay for things that you do not need.
see the difference between atomic and nonatomic in objective c
Atomic
Atomic is the default behaviour for a property; by not explicitly setting the above property as nonatomic, it will be atomic.
An atomic property adds a level of thread safety when getting or setting values. That is, the getter and setter for the property will always be fully completed regardless of what other threads are doing. The trade-off is that these properties will be a little slower to access than a nonatomic equivalent.
Non-Atomic
Nonatomic properties are not thread safe, and will return their properties directly. This will be faster than atomic properties, but obviously carries some risk if precautions aren’t made.
#property (strong) NSString *str;
Atomic is the default behaviour for a property; by not explicitly setting the above property as nonatomic, it will be atomic.
setter & getter for these Atomic property
-(NSString *) str{
#synchronized(self){
return str;
}}
-(void) setStr: (NSString *) newString {
#synchronized(self)  {
str = newString;
}}
An atomic property adds a level of thread safety when getting or setting values. That is, the getter and setter for the property will always be fully completed regardless of what other threads are doing. these properties will be a little slower to access than a nonatomic equivalent.
#property (strong,nonatomic) NSString *str;
Nonatomic properties are not thread safe, and will return their properties directly. This will be faster than atomic properties, but obviously carries some risk if precautions aren’t made.
setter & getter for these Nonatomic property
-(NSString *) str{
return str;
}}
-(void) setStr: (NSString *) newString{
str = newString;
}
So by looking on the setter & getter methods for both Atomic & nonatomic that nonatomic methods are very light weight.

iOS property declaration clarification

This is a two part question in hopes that I can understand more about the topic.
1) It seems to me that you have two popular options for declaring a property for a class in objective c. One is to add the property to the header's class body eg.
#interface MyClass : NSObject {
NSArray *myArray;
}
Or you can add it after the #interface body and before the #end statement like so.
#interface MyClass : NSObject {
//
}
#property (nonatomic, retain) NSArray *myArray;
What is the difference between these two "styles" and when do you choose one over the other?
2) after the #property you find options such as (nonatomic, retain). What are those for and why/when do you use different options?
Here are the only property modifiers that Xcode recognizes:
nonatomic (does not enforce thread safety on the property, mainly for use when only one thread shall be used throughout a program)
atomic (enforces thread safety on the property, mainly for use when multiple threads shall be used throughout a program) (default)
retain / strong (automatically retains / releases values on set, makes sure values do not deallocate unexpectedly) (default if ARC and object type)
readonly (cannot set property)
readwrite (can both set and get property) (default)
assign / unsafe_unretained (no memory management shall be done with this property, it is handled manually by the person assigning the value) (default if not ARC or object type)
copy (copies the object before setting it, in cases where the value set must not change due to external factors (strings, arrays, etc).
weak (automatically zeroes the reference should the object be deallocated, and does not retain the value passed in)
getter=method (sets the selector used for getting the value of this property)
setter= method (set the selector used for setting the value of this property)
1) #property is a special way to define getter- and setter-methods, or as we call them accessors in Objective-C. Your first snippet just declares an array for which you have to declare and write accessors yourself. For example setMyArray: and myArray.
Using #property will declare your accessors for you and is equivalent to declaring setMyArray: and myArray yourself. It is the preferred way to declare accessors since Objective-C 2.0. Note that you still have to declare the property (in your case myArray) yourself.
2) You first need to know about #synthesize. Remember that #property DECLARES the accessors for your property, #synthesize will IMPLEMENT them. When you use an #property in your #interface you mostly likely write an #synthesize in #implementation. Using #synthesize is equivalent to implementing setMyArray: and myArray.
The attributes (nonatomic, retain) tell the compiler, among others, how the memory management should work and therefore how the methods will be implemented. Note that you never actually see these accessors, but be assured that they are there and ready for you to be used.
To read more on that topic I recommend reading Section 9 on Properties from the following Tutorial or buy a Book that covers an Introduction to Objective-C.
Also you should familiarize yourself with at least the following attributes:
Access
Choose readwrite (default) or readonly. If readonly is set, ONLY the getter methods will be available.
Setter Memory Management
assign (default), simply assigns the new value. You mostly likely only use this with primitive data types.
retain, releases the old value and retains the new. If you use the garbage collector, retain is equivalent to assign. Why? The manual release of the old value will be done by the garbage collector.
copy will copy the new value and release the old value. This is often used with strings.
Threading
atomic (default) will ensure that the setter method is atomic. This means only one thread can access the setter at once.
nonatomic, use this when you don't work with threads.
This post gives you a good introduction to memory management and assign, retain and copy.
Properties are basically the accessor methods. They define the scope of the variable.
First case as given above,the variable is not accessible in other classes whereas by declaring a property as in the second case,variable is accessible in other classes also.
Also, they are useful for memory management.
First one will be private declaration and will not be accessible by other classes if you do not define the second one. Second is used together with #synthesize in .m module , and setter/getter's are created for you by the compiler. You can still define your own getter or setter with this. In this case all iVars defined in #property can be accessed by other classes.Retain/release operations are done automatically.
You should read Apple documentation for more details.
please check:
What's the difference between the atomic and nonatomic attributes?
Properties are basically the accessor methods. They define the scope of the variable. by default access specifior of variable is protected and properties set its Specifier from protected to Public

What are the defaults values for #property in iOS?

What are the defaults values for #property in iOS ?
For example, if I declare #property NSString* photographer;
is the default value (assign) or (retain) or what else ?
(atomic, non-atomic) ?
I cannot find this information from the documentation.
thanks
I believe the defaults are (atomic, assign), however, you should not leave them empty.
The default may change at any point, and you're writing code that is relying on the definition of the property.
For example, if you rely on the default assign and it changes to retain for whatever reason in the future, then all of your code is going to leak.
Conversely, if the default is retain and you rely on that and it changes to assign, then your code is going to crash when you inevitably over release an object.
Do not rely on any default, regardless of what they may be.
Explicitly define your properties' attributes.
Properties are atomic by default so that synthesized accessors provide robust access to properties in a multithreaded environment—that is, the value returned from the getter or set via the setter is always fully retrieved or set regardless of what other threads are executing concurrently.
If you specify strong, copy, or retain and do not specify nonatomic, then in a reference-counted environment, a synthesized get accessor for an object property uses a lock and retains and autoreleases the returned value.
I don't think Apple will change it in the future, but unfortunately the most common is non atomic, so you may have to write it down.

What's the difference between the atomic and nonatomic attributes?

What do atomic and nonatomic mean in property declarations?
#property(nonatomic, retain) UITextField *userName;
#property(atomic, retain) UITextField *userName;
#property(retain) UITextField *userName;
What is the operational difference between these three?
The last two are identical; "atomic" is the default behavior (note that it is not actually a keyword; it is specified only by the absence of nonatomic -- atomic was added as a keyword in recent versions of llvm/clang).
Assuming that you are #synthesizing the method implementations, atomic vs. non-atomic changes the generated code. If you are writing your own setter/getters, atomic/nonatomic/retain/assign/copy are merely advisory. (Note: #synthesize is now the default behavior in recent versions of LLVM. There is also no need to declare instance variables; they will be synthesized automatically, too, and will have an _ prepended to their name to prevent accidental direct access).
With "atomic", the synthesized setter/getter will ensure that a whole value is always returned from the getter or set by the setter, regardless of setter activity on any other thread. That is, if thread A is in the middle of the getter while thread B calls the setter, an actual viable value -- an autoreleased object, most likely -- will be returned to the caller in A.
In nonatomic, no such guarantees are made. Thus, nonatomic is considerably faster than "atomic".
What "atomic" does not do is make any guarantees about thread safety. If thread A is calling the getter simultaneously with thread B and C calling the setter with different values, thread A may get any one of the three values returned -- the one prior to any setters being called or either of the values passed into the setters in B and C. Likewise, the object may end up with the value from B or C, no way to tell.
Ensuring data integrity -- one of the primary challenges of multi-threaded programming -- is achieved by other means.
Adding to this:
atomicity of a single property also cannot guarantee thread safety when multiple dependent properties are in play.
Consider:
#property(atomic, copy) NSString *firstName;
#property(atomic, copy) NSString *lastName;
#property(readonly, atomic, copy) NSString *fullName;
In this case, thread A could be renaming the object by calling setFirstName: and then calling setLastName:. In the meantime, thread B may call fullName in between thread A's two calls and will receive the new first name coupled with the old last name.
To address this, you need a transactional model. I.e. some other kind of synchronization and/or exclusion that allows one to exclude access to fullName while the dependent properties are being updated.
This is explained in Apple's documentation, but below are some examples of what is actually happening.
Note that there is no "atomic" keyword, if you do not specify "nonatomic", then the property is atomic, but specifying "atomic" explicitly will result in an error.
If you do not specify "nonatomic", then the property is atomic, but you can still specify "atomic" explicitly in recent versions if you want to.
//#property(nonatomic, retain) UITextField *userName;
//Generates roughly
- (UITextField *) userName {
return userName;
}
- (void) setUserName:(UITextField *)userName_ {
[userName_ retain];
[userName release];
userName = userName_;
}
Now, the atomic variant is a bit more complicated:
//#property(retain) UITextField *userName;
//Generates roughly
- (UITextField *) userName {
UITextField *retval = nil;
#synchronized(self) {
retval = [[userName retain] autorelease];
}
return retval;
}
- (void) setUserName:(UITextField *)userName_ {
#synchronized(self) {
[userName_ retain];
[userName release];
userName = userName_;
}
}
Basically, the atomic version has to take a lock in order to guarantee thread safety, and also is bumping the ref count on the object (and the autorelease count to balance it) so that the object is guaranteed to exist for the caller, otherwise there is a potential race condition if another thread is setting the value, causing the ref count to drop to 0.
There are actually a large number of different variants of how these things work depending on whether the properties are scalar values or objects, and how retain, copy, readonly, nonatomic, etc interact. In general the property synthesizers just know how to do the "right thing" for all combinations.
Atomic
is the default behavior
will ensure the present process is completed by the CPU, before another process accesses the variable
is not fast, as it ensures the process is completed entirely
Non-Atomic
is NOT the default behavior
faster (for synthesized code, that is, for variables created using #property and #synthesize)
not thread-safe
may result in unexpected behavior, when two different process access the same variable at the same time
The best way to understand the difference is using the following example.
Suppose there is an atomic string property called "name", and if you call [self setName:#"A"] from thread A, call [self setName:#"B"] from thread B, and call [self name] from thread C, then all operations on different threads will be performed serially which means if one thread is executing a setter or getter, then other threads will wait.
This makes property "name" read/write safe, but if another thread, D, calls [name release] simultaneously then this operation might produce a crash because there is no setter/getter call involved here. Which means an object is read/write safe (ATOMIC), but not thread-safe as another threads can simultaneously send any type of messages to the object. The developer should ensure thread-safety for such objects.
If the property "name" was nonatomic, then all threads in above example - A,B, C and D will execute simultaneously producing any unpredictable result. In case of atomic, either one of A, B or C will execute first, but D can still execute in parallel.
The syntax and semantics are already well-defined by other excellent answers to this question. Because execution and performance are not detailed well, I will add my answer.
What is the functional difference between these 3?
I'd always considered atomic as a default quite curious. At the abstraction level we work at, using atomic properties for a class as a vehicle to achieve 100% thread-safety is a corner case. For truly correct multithreaded programs, intervention by the programmer is almost certainly a requirement. Meanwhile, performance characteristics and execution have not yet been detailed in depth. Having written some heavily multithreaded programs over the years, I had been declaring my properties as nonatomic the entire time because atomic was not sensible for any purpose. During discussion of the details of atomic and nonatomic properties this question, I did some profiling encountered some curious results.
Execution
Ok. The first thing I would like to clear up is that the locking implementation is implementation-defined and abstracted. Louis uses #synchronized(self) in his example -- I have seen this as a common source of confusion. The implementation does not actually use #synchronized(self); it uses object level spin locks. Louis's illustration is good for a high-level illustration using constructs we are all familiar with, but it's important to know it does not use #synchronized(self).
Another difference is that atomic properties will retain/release cycle your objects within the getter.
Performance
Here's the interesting part: Performance using atomic property accesses in uncontested (e.g. single-threaded) cases can be really very fast in some cases. In less than ideal cases, use of atomic accesses can cost more than 20 times the overhead of nonatomic. While the Contested case using 7 threads was 44 times slower for the three-byte struct (2.2 GHz Core i7 Quad Core, x86_64). The three-byte struct is an example of a very slow property.
Interesting side note: User-defined accessors of the three-byte struct were 52 times faster than the synthesized atomic accessors; or 84% the speed of synthesized nonatomic accessors.
Objects in contested cases can also exceed 50 times.
Due to the number of optimizations and variations in implementations, it's quite difficult to measure real-world impacts in these contexts. You might often hear something like "Trust it, unless you profile and find it is a problem". Due to the abstraction level, it's actually quite difficult to measure actual impact. Gleaning actual costs from profiles can be very time consuming, and due to abstractions, quite inaccurate. As well, ARC vs MRC can make a big difference.
So let's step back, not focussing on the implementation of property accesses, we'll include the usual suspects like objc_msgSend, and examine some real-world high-level results for many calls to a NSString getter in uncontested cases (values in seconds):
MRC | nonatomic | manually implemented getters: 2
MRC | nonatomic | synthesized getter: 7
MRC | atomic | synthesized getter: 47
ARC | nonatomic | synthesized getter: 38 (note: ARC's adding ref count cycling here)
ARC | atomic | synthesized getter: 47
As you have probably guessed, reference count activity/cycling is a significant contributor with atomics and under ARC. You would also see greater differences in contested cases.
Although I pay close attention to performance, I still say Semantics First!. Meanwhile, performance is a low priority for many projects. However, knowing execution details and costs of technologies you use certainly doesn't hurt. You should use the right technology for your needs, purposes, and abilities. Hopefully this will save you a few hours of comparisons, and help you make a better informed decision when designing your programs.
Atomic = thread safety
Non-atomic = No thread safety
Thread safety:
Instance variables are thread-safe if they behave correctly when accessed from multiple threads, regardless of the scheduling or interleaving of the execution of those threads by the runtime environment, and with no additional synchronization or other coordination on the part of the calling code.
In our context:
If a thread changes the value of the instance the changed value is available to all the threads, and only one thread can change the value at a time.
Where to use atomic:
if the instance variable is gonna be accessed in a multithreaded environment.
Implication of atomic:
Not as fast as nonatomic because nonatomic doesn't require any watchdog work on that from runtime .
Where to use nonatomic:
If the instance variable is not gonna be changed by multiple threads you can use it. It improves the performance.
After reading so many articles, Stack Overflow posts and making demo applications to check variable property attributes, I decided to put all the attributes information together:
atomic // Default
nonatomic
strong = retain // Default
weak = unsafe_unretained
retain
assign // Default
unsafe_unretained
copy
readonly
readwrite // Default
In the article Variable property attributes or modifiers in iOS you can find all the above-mentioned attributes, and that will definitely help you.
atomic
atomic means only one thread access the variable (static type).
atomic is thread safe.
But it is slow in performance
atomic is the default behavior
Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value.
It is not actually a keyword.
Example:
#property (retain) NSString *name;
#synthesize name;
nonatomic
nonatomic means multiple thread access the variable (dynamic type).
nonatomic is thread-unsafe.
But it is fast in performance
nonatomic is NOT default behavior. We need to add the nonatomic keyword in the property attribute.
It may result in unexpected behavior, when two different process (threads) access the same variable at the same time.
Example:
#property (nonatomic, retain) NSString *name;
#synthesize name;
I found a pretty well put explanation of atomic and non-atomic properties here. Here's some relevant text from the same:
'atomic' means it cannot be broken down.
In OS/programming terms an atomic function call is one that cannot be interrupted - the entire function must be executed, and not swapped out of the CPU by the OS's usual context switching until it's complete. Just in case you didn't know: since the CPU can only do one thing at a time, the OS rotates access to the CPU to all running processes in little time-slices, to give the illusion of multitasking. The CPU scheduler can (and does) interrupt a process at any point in its execution - even in mid function call. So for actions like updating shared counter variables where two processes could try to update the variable at the same time, they must be executed 'atomically', i.e., each update action has to finish in its entirety before any other process can be swapped onto the CPU.
So I'd be guessing that atomic in this case means the attribute reader methods cannot be interrupted - in effect meaning that the variable(s) being read by the method cannot change their value half way through because some other thread/call/function gets swapped onto the CPU.
Because the atomic variables can not be interrupted, the value contained by them at any point is (thread-lock) guaranteed to be uncorrupted, although, ensuring this thread lock makes access to them slower. non-atomic variables, on the other hand, make no such guarantee but do offer the luxury of quicker access. To sum it up, go with non-atomic when you know your variables won't be accessed by multiple threads simultaneously and speed things up.
Atomic :
Atomic guarantees that access to the property will be performed in an atomic manner. E.g. it always return a fully initialised objects, any get/set of a property on one thread must complete before another can access it.
If you imagine the following function occurring on two threads at once you can see why the results would not be pretty.
-(void) setName:(NSString*)string
{
if (name)
{
[name release];
// what happens if the second thread jumps in now !?
// name may be deleted, but our 'name' variable is still set!
name = nil;
}
...
}
Pros :
Return of fully initialised objects each time makes it best choice in case of multi-threading.
Cons :
Performance hit, makes execution a little slower
Non-Atomic :
Unlike Atomic, it doesn't ensure fully initialised object return each time.
Pros :
Extremely fast execution.
Cons :
Chances of garbage value in case of multi-threading.
Easiest answer first: There's no difference between your second two examples. By default, property accessors are atomic.
Atomic accessors in a non garbage collected environment (i.e. when using retain/release/autorelease) will use a lock to ensure that another thread doesn't interfere with the correct setting/getting of the value.
See the "Performance and Threading" section of Apple's Objective-C 2.0 documentation for some more information and for other considerations when creating multi-threaded apps.
Atomic means only one thread accesses the variable (static type). Atomic is thread-safe, but it is slow.
Nonatomic means multiple threads access the variable (dynamic type). Nonatomic is thread-unsafe, but it is fast.
Atomic is thread safe, it is slow and it well-assures (not guaranteed) that only the locked value is provided no matter how many threads are attempting access over the same zone. When using atomic, a piece of code written inside this function becomes the part of the critical section, to which only one thread can execute at a time.
It only assures the thread safety; it does not guarantee that. What I mean is you hire an expert driver for you car, still it doesn't guarantees car won't meet an accident. However, probability remains the slightest.
Atomic - it can't be broken down, so the result is expected. With nonatomic - when another thread access the memory zone it can modify it, so the result is unexpected.
Code Talk :
Atomic make getter and setter of the property thread safe. for example if u have written :
self.myProperty = value;
is thread safe.
[myArray addObject:#"Abc"]
is NOT thread safe.
atomic (default)
Atomic is the default: if you don’t type anything, your property is
atomic. An atomic property is guaranteed that if you try to read from
it, you will get back a valid value. It does not make any guarantees
about what that value might be, but you will get back good data, not
just junk memory. What this allows you to do is if you have multiple
threads or multiple processes pointing at a single variable, one
thread can read and another thread can write. If they hit at the same
time, the reader thread is guaranteed to get one of the two values:
either before the change or after the change. What atomic does not
give you is any sort of guarantee about which of those values you
might get. Atomic is really commonly confused with being thread-safe,
and that is not correct. You need to guarantee your thread safety
other ways. However, atomic will guarantee that if you try to read,
you get back some kind of value.
nonatomic
On the flip side, non-atomic, as you can probably guess, just means,
“don’t do that atomic stuff.” What you lose is that guarantee that you
always get back something. If you try to read in the middle of a
write, you could get back garbage data. But, on the other hand, you go
a little bit faster. Because atomic properties have to do some magic
to guarantee that you will get back a value, they are a bit slower. If
it is a property that you are accessing a lot, you may want to drop
down to nonatomic to make sure that you are not incurring that speed
penalty.
See more here: https://realm.io/news/tmi-objective-c-property-attributes/
There is no such keyword "atomic"
#property(atomic, retain) UITextField *userName;
We can use the above like
#property(retain) UITextField *userName;
See Stack Overflow question I am getting issues if I use #property(atomic,retain)NSString *myString.
The default is atomic, this means it does cost you performance whenever you use the property, but it is thread safe. What Objective-C does, is set a lock, so only the actual thread may access the variable, as long as the setter/getter is executed.
Example with MRC of a property with an ivar _internal:
[_internal lock]; //lock
id result = [[value retain] autorelease];
[_internal unlock];
return result;
So these last two are the same:
#property(atomic, retain) UITextField *userName;
#property(retain) UITextField *userName; // defaults to atomic
On the other hand does nonatomic add nothing to your code. So it is only thread safe if you code security mechanism yourself.
#property(nonatomic, retain) UITextField *userName;
The keywords doesn't have to be written as first property attribute at all.
Don't forget, this doesn't mean that the property as a whole is thread-safe. Only the method call of the setter/getter is. But if you use a setter and after that a getter at the same time with 2 different threads, it could be broken too!
-Atomic means only one thread access the variable(static type).
-Atomic is thread safe.
-but it is slow in performance
How to declare:
As atomic is default so,
#property (retain) NSString *name;
AND in implementation file
self.name = #"sourov";
Suppose a task related to three properties are
#property (retain) NSString *name;
#property (retain) NSString *A;
#property (retain) NSString *B;
self.name = #"sourov";
All properties work parallelly (like asynchronously).
If you call "name" from thread A,
And
At the same time if you call
[self setName:#"Datta"]
from thread B,
Now If *name property is nonatomic then
It will return value "Datta" for A
It will return value "Datta" for B
Thats why non atomic is called thread unsafe But but it is fast in performance because of parallel execution
Now If *name property is atomic
It will ensure value "Sourov" for A
Then It will return value "Datta" for B
That's why atomic is called thread Safe and
That's why it is called read-write safe
Such situation operation will perform serially.
And Slow in performance
- Nonatomic means multiple thread access the variable(dynamic type).
- Nonatomic is thread unsafe.
- but it is fast in performance
-Nonatomic is NOT default behavior, we need to add nonatomic keyword in property attribute.
For In Swift
Confirming that Swift properties are nonatomic in the ObjC sense. One reason is so you think about whether per-property atomicity is sufficient for your needs.
Reference: https://forums.developer.apple.com/thread/25642
Fro more info please visit the website
http://rdcworld-iphone.blogspot.in/2012/12/variable-property-attributes-or.html
If you are using your property in multi-threaded code then you would be able to see the difference between nonatomic and atomic attributes. Nonatomic is faster than atomic and atomic is thread-safe, not nonatomic.
Vijayendra Tripathi has already given an example for a multi-threaded environment.
Before you begin: You must know that every object in memory needs to be deallocated from memory for a new writer to happen. You can't just simply write on top of something as you do on paper. You must first erase (dealloc) it and then you can write onto it. If at the moment that the erase is done (or half done) and nothing has yet been wrote (or half wrote) and you try to read it could be very problematic! Atomic and nonatomic help you treat this problem in different ways.
First read this question and then read Bbum's answer. In addition, then read my summary.
atomic will ALWAYS guarantee
If two different people want to read and write at the same time, your paper won't just burn! --> Your application will never crash, even in a race condition.
If one person is trying to write and has only written 4 of the 8 letters to write, then no can read in the middle, the reading can only be done when all 8 letters is written --> No read(get) will happen on 'a thread that is still writing', i.e. if there are 8 bytes to bytes to be written, and only 4 bytes are written——up to that moment, you are not allowed to read from it. But since I said it won't crash then it would read from the value of an autoreleased object.
If before writing you have erased that which was previously written on paper and then someone wants to read you can still read. How? You will be reading from something similar to Mac OS Trash bin ( as Trash bin is not still 100% erased...it's in a limbo) ---> If ThreadA is to read while ThreadB has already deallocated to write, you would get a value from either the final fully written value by ThreadB or get something from autorelease pool.
Retain counts are the way in which memory is managed in Objective-C.
When you create an object, it has a retain count of 1. When you send
an object a retain message, its retain count is incremented by 1. When
you send an object a release message, its retain count is decremented
by 1. When you send an object an autorelease message, its retain count
is decremented by 1 at some stage in the future. If an objectʼs retain
count is reduced to 0, it is deallocated.
Atomic doesn't guarantee thread safety, though it's useful for achieving thread safety. Thread Safety is relative to how you write your code/ which thread queue you are reading/writing from. It only guarantees non-crashable multithreading.
What?! Are multithreading and thread safety different?
Yes. Multithreading means: multiple threads can read a shared piece of data at the same time and we will not crash, yet it doesn't guarantee that you aren't reading from a non-autoreleased value. With thread safety, it's guaranteed that what you read is not auto-released.
The reason that we don't make everything atomic by default is, that there is a performance cost and for most things don't really need thread safety. A few parts of our code need it and for those few parts, we need to write our code in a thread-safe way using locks, mutex or synchronization.
nonatomic
Since there is no such thing like Mac OS Trash Bin, then nobody cares whether or not you always get a value (<-- This could potentially lead to a crash), nor anybody cares if someone tries to read halfway through your writing (although halfway writing in memory is very different from halfway writing on paper, on memory it could give you a crazy stupid value from before, while on paper you only see half of what's been written) --> Doesn't guarantee to not crash, because it doesn't use autorelease mechanism.
Doesn't guarantee full written values to be read!
Is faster than atomic
Overall they are different in 2 aspects:
Crashing or not because of having or not having an autorelease pool.
Allowing to be read right in the middle of a 'not yet finished write or empty value' or not allowing and only allowing to read when the value is fully written.
Atomicity
atomic (default)
Atomic is the default: if you don’t type anything, your property is
atomic. An atomic property is guaranteed that if you try to read from
it, you will get back a valid value. It does not make any guarantees
about what that value might be, but you will get back good data, not
just junk memory. What this allows you to do is if you have multiple
threads or multiple processes pointing at a single variable, one
thread can read and another thread can write. If they hit at the same
time, the reader thread is guaranteed to get one of the two values:
either before the change or after the change. What atomic does not
give you is any sort of guarantee about which of those values you
might get. Atomic is really commonly confused with being thread-safe,
and that is not correct. You need to guarantee your thread safety
other ways. However, atomic will guarantee that if you try to read,
you get back some kind of value.
nonatomic
On the flip side, non-atomic, as you can probably guess, just means,
“don’t do that atomic stuff.” What you lose is that guarantee that you
always get back something. If you try to read in the middle of a
write, you could get back garbage data. But, on the other hand, you go
a little bit faster. Because atomic properties have to do some magic
to guarantee that you will get back a value, they are a bit slower. If
it is a property that you are accessing a lot, you may want to drop
down to nonatomic to make sure that you are not incurring that speed
penalty. Access
courtesy https://academy.realm.io/posts/tmi-objective-c-property-attributes/
Atomicity property attributes (atomic and nonatomic) are not reflected in the corresponding Swift property declaration, but the atomicity guarantees of the Objective-C implementation still hold when the imported property is accessed from Swift.
So — if you define an atomic property in Objective-C it will remain atomic when used by Swift.
courtesy
https://medium.com/#YogevSitton/atomic-vs-non-atomic-properties-crash-course-d11c23f4366c
The atomic property ensures to retain a fully initialised value irrespective of how many threads are doing getter & setter on it.
The nonatomic property specifies that synthesized accessors simply set or return a value directly, with no guarantees about what happens if that same value is accessed simultaneously from different threads.
Atomic means only one thread can access the variable at a time (static type). Atomic is thread-safe, but it is slow.
Nonatomic means multiple threads can access the variable at same time (dynamic type). Nonatomic is thread-unsafe, but it is fast.
The truth is that they use spin lock to implement atomic property. The code as below:
static inline void reallySetProperty(id self, SEL _cmd, id newValue,
ptrdiff_t offset, bool atomic, bool copy, bool mutableCopy)
{
id oldValue;
id *slot = (id*) ((char*)self + offset);
if (copy) {
newValue = [newValue copyWithZone:NULL];
} else if (mutableCopy) {
newValue = [newValue mutableCopyWithZone:NULL];
} else {
if (*slot == newValue) return;
newValue = objc_retain(newValue);
}
if (!atomic) {
oldValue = *slot;
*slot = newValue;
} else {
spin_lock_t *slotlock = &PropertyLocks[GOODHASH(slot)];
_spin_lock(slotlock);
oldValue = *slot;
*slot = newValue;
_spin_unlock(slotlock);
}
objc_release(oldValue);
}
In a single line:
Atomic is thread safe. Nonatomic is thread-unsafe.
If you are using atomic, it means the thread will be safe and read-only. If you are using nonatomic, it means the multiple threads access the variable and is thread unsafe, but it is executed fast, done a read and write operations; this is a dynamic type.
Atomic: Ensure thread-safety by locking the thread using NSLOCK.
Non atomic: Doesn't ensure thread-safety as there is no thread-locking mechanism.
To simplify the entire confusion, let us understand mutex lock.
Mutex lock, as per the name, locks the mutability of the object. So if the object is accessed by a class, no other class can access the same object.
In iOS, #sychronise also provides the mutex lock .Now it serves in FIFO mode and ensures the flow is not affected by two classes sharing the same instance. However, if the task is on main thread, avoid accessing object using atomic properties as it may hold your UI and degrade the performance.
Atomic properties :- When a variable assigned with atomic property that means it has only one thread access and it will be thread safe and will be slow in performance perspective, will have default behaviour.
Non Atomic Properties :- When a variable assigned with nonatomic property that means it has multi thread access and it will not be thread safe and will be fast in performance perspective, will have default behaviour and when two different threads want to access variable at same time it will give unexpected results.

Resources