1. assume that you allocated a piece of memory with malloc and assigned its address to pointer A. Then you want pointer B to share the block of memory, so you assign a value to assign) b. At this time, a and B point to the same memory. Can a directly release this memory when a no longer needs it? The answer is no, because a does not know whether B is still using this memory. If a is released, B will cause Program Crash.
2. I learned about the assign problem in 1. How can I solve it? The simplest way is to use reference counting. In the example above, we set a reference count for the memory. When the memory is allocated and assigned to, the reference count is 1. When a is assigned to B, the reference count is increased to 2. If a no longer uses this memory, it only needs to reduce the reference count by 1, indicating that it no longer owns this memory. When B no longer uses this memory, it also reduces the reference count by 1. When the reference count is 0, it indicates that the memory is no longer referenced by any pointer, and the system can release it directly.
3. The above two points are actually the differences between assign and retain. Assign is a direct value assignment, which may cause problems in 1. When the data is of native types such as int and float, assign can be used. As described in section 2, retain uses the reference count. Retain causes the reference count to increase by 1, and release causes the reference count to decrease by 1. When the reference count is 0, the dealloc function is called, memory is recycled.
4. Copy is used when you do not want a and B to share a piece of memory. A and B each have their own memory.
5. Atomic and nonatomic are used to determine whether the getter and setter generated by the compiler are atomic operations. In a multi-threaded environment, atomic operations are necessary; otherwise, errors may occur. With Atomic added, the setter function will become as follows:
- If (property! = Newvalue) {
- [property release];
- property = [newvalue retain];
- }