A Memory Leak refers to a program that fails to release dynamically allocated heap Memory for some reason, resulting in a waste of system Memory, slowing down the program and even crashing the system. — Baidu Encyclopedia
1. Causes of memory leaks
Self. Timer = Timer. ScheduledTimer (timeInterval: 1, target: self, selector: #selector(updateTimer(_ :)), userInfo: nil, repeats: true) Class A {var b: b} class A {var b: b} class b {var A: A} let A = A() let b = b () a.b = b b.a = A Class A {var avtion: (()->())? } class B{var a: a = a () func xx(){a.tion = {self.xxx//(use self to do some work)}} Use [weak self] or [unowned self] to avoid cyclic references a.action = {[weak self] in guard let 'self' = self else The unowned modifier is similar to OC's assign. Self refers to the address of the current object. If the object has been freed, make sure self is not set to nil No release, otherwise there will be a wild pointer error.Copy the code
2. Check for memory leaks
1. Static analysis: From the Xcode menu bar, click "Product" and select Analyze (Command + Shift + B). Xcode will Analyze statements that may cause leaks.Copy the code
Leaks Product => Profile(Command+I) => Leaks Click the record-like button in the upper left corner to start detectionCopy the code
3. Debug Memory Graph
Copy the code
Next to the view hierarchy button in the background output box, if we already know that an object has not been freed (for example, controller pop), we can use this method to see who strongly referenced it.Copy the code
4. Manual retrieval (laughter) Command + F searches for self in a controller that knows it has not been freed, and then searches to see if there is any self in the block that you accidentally used that has no weak handling. Simple violence fool style (thing brushed clothes go, deep hide with name)Copy the code