Things you should pay attention to when writing OC code: memory management

1. Understanding reference counting

(1) Working principle: retain: increment reserved words, release: decrement reserved words, autorelease: clean up the "auto-release pool" later and decrement the retention count.

(2) The reference counting mechanism manages memory through a calculator that can be incremented and decremented. After the object is created, its retention count is at least 1. If the retention count is positive, it will not be released if it wants to continue to survive. When the count reaches 0, the object is destroyed.

(3) During the object life cycle, other objects retain and release the object through the reference counting mechanism. Reserve and release operations increment and decrement the retain count respectively.

2.ARC uses simplified reference counting

(1) When using ARC, you must follow the method naming rules: method names starting with the words alloc, new, copy, and mtublecopy return objects that are owned by the caller. Whoever calls it is responsible for releasing the object returned by the method.

(2) ARC will borrow the destructor of the OC++ object to perform the code required to clean up the memory.

(3) Only release the application and unlisten in the dealloc method.

(4) Pay attention to memory management issues when writing "exception-safe code".

3. Use weak references to avoid retention cycles

(1) When there are mutual references, memory leaks may easily occur and the memory cannot be released.

(2) Usually the attribute value is set to weak attribute to avoid retention loop.

4. Use automatic release blocks to reduce memory peaks: There are two ways to release objects: call release and call autorelease.

(1) Put the loop object into the automatic release pool, and the memory peak of the application when executing the loop will be reduced.

(2) Properly use the automatic release pool to reduce the peak value of the application.

5. Use zombie objects to debug memory management issues

(1) Enablement method: Set the NSZombieEnabled environment variable to YES to enable the function.

(2) The returnCount method is abolished under ARC, and it is best not to use the retainCount function in MRC. Because this function may never return 0, because this object may be recycled by the system when the retention count is still 1, because the system may optimize.

Guess you like

Origin blog.csdn.net/weixin_42357849/article/details/122132974