- When declaring a property of a class, the default property is decorated with atomic, meaning atomic access.
The properties of nonatomic and atomic are modified without rewriting the setter and getter, and its main function can be understood as the atomic modified setter and getter are mutually exclusive under multithreading, The equivalent of the start and end of the setter and getter is locked.
StackOverflow above the answer to the atomic interpretation of the most agreed:
Atomic is not equal to thread safety, for common references, pointers, 4-byte (bit-wide byte) variables, the assignment operation itself is atomic, there is no need to add atomic, for the structure type, atomic will play a role.
Thread Safety
Thread safety problem refers to the problem of memory disturbance caused by multiple threads reading and writing shared variables, and to solve the problem of thread safety, it is necessary to ensure that the code sequence is serial when the same variable is read and written. In addition to using thread-safe methods and locking, common methods can also place read-write code in the same queue.
Apple gives some classes that are thread insecure, and the objects (variables) created by these classes are unsafe to access in multiple threads. Normally immutable objects (immutable) are thread-safe, and the objects that can be changed are not thread-safe (mutable).
Thread-Safe classes:
-
NSArray
-
NSAssertionHandler
-
NSAttributedString
-
NSCalendarDate
-
NSCharacterSet
-
NSConditionLock
-
NSConnection
-
NSData
-
NSDate
-
NSDecimalFunctions
-
NSDecimalNumber
-
NSDecimalNumberHandler
-
NSDeserializer
-
NSDictionary
-
NSDistantObject
-
NSDistributedLock
-
NSDistributedNotificationCenter
-
NSException
-
NSFileManager(In OS X v10.5 and later)
-
NSHost
-
NSLock
-
NSLog/NSLogv
-
NSMethodSignature
-
NSNotification
-
NSNotificationCenter
-
NSNumber
-
NSObject
-
NSPortCoder
-
NSPortMessage
-
NSPortNameServer
-
NSProtocolChecker
-
NSProxy
-
NSRecursiveLock
-
NSSet
-
NSString
-
NSThread
-
NSTimer
-
NSTimeZone
-
NSUserDefaults
-
NSValue
-
NSXMLParser
-
Object allocation and retain count functions
-
Zone and Memory functions
Thread unsafe classes:
例如这样声明的对象:
@property (nonatomic , strong) NSMutableArray * array;
array在多线程访问,比如一个线程遍历数组,另外一个线程删除或者插入元素时,程序会直接crash,提示指针异常。同样的道理,atomic修饰的属性,并不能保证多线程读写对象内部元素的安全性,因此atomic不是线程安全的。
The property modifier for the IOS class atomic