Strange Undetectable memory leak

Viewed 126

I manually created a memory leak, but the Debug Memory Graph cannot detect it. This only happens on the controller, not on the general object type. Any one konw why? enter image description here

This is the code I used

import UIKit
class ViewController: UIViewController {
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        present(Demo(), animated: true, completion: nil)
    }
}
class Demo : UIViewController {
    var obj:Demo?
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemTeal
        obj = self
    }
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        dismiss(animated: true, completion: nil)
    }
}
1 Answers

It's look like that UIViewController begin observation of UIApplicationSuspendedNotification.

There is 2 method to begin of observations:

  1. addObserver(_:selector:name:object:)
  2. addObserver(forName:object:queue:using:) Both keep weak reference to our Demo view controller. Demo vc is addObserver through first method. It's seems that apple didn't consider as memory leaks object's that observing NotificationCenter.

I get this information through follow debugging steps:

1. After opening debugger with enabled with enabled Malloc Stack Logging in project scheme i find out __NSObservers references. enter image description here

2. Then i look at Backtrace and find out that there is a calls to [NSNotificationCenter addObserver:selector:name:object:]. enter image description here

  1. Im added sybmolic breakpoint with method name [NSNotificationCenter addObserver:selector:name:object:] and printed all argument $arg1 $arg2 $arg3 $arg4 $arg5 $arg6 and find the name of observation.

  2. Using the address of NotificationCenter and and adress of my ViewController, i'm deleted the observation through [ NotificationCenterAdress removeObserver:ViewControllerAdress] and reopened memory debugger. And debugger treats viewController as memory leak. (there is 12 instances on screenshot because i taped on background multiple times). enter image description here

Related