Swift - How to find all instances of a class, and all references that point to the same instance?

Viewed 1052

I inherited an application where certain class is instantiated and passed back and forth multiple times. So I have about 20 private and public variables where

  1. Class instantiates: myClass = MyClass()
  2. MyClass instance is passed back and forth: self.myClass = someOtherClass.myClass
  3. Sometimes variable is passed from class to class multiple times
  4. And a class may create a new instance or receive an instance from some other class in various cases

I want to fix this. But before changing anything I want to understand how many instances of that class I have, and which references point to the same instance.

What I do now: I am running the following statement in each method of MyClass:

print(Unmanaged.passUnretained(self).toOpaque())

and then additional prints in callers to identify who called that instance. This is quite tedious, but moreover it completely depends on my ability to cover all possible cases if this class usage at runtime, and it won't find nil references that classes may pass to each other (and which I need to know of)

So is there a better way? Or can this method be improved in some way?

Thanks in advance.

1 Answers

Sounds simple but why not add a static variable to the class in question and increment it in the init method?

This way you’ll have a definite count of the number of instances.

(Decrement it in the deinit() of course)

Failing that you could have a “global” variable type MyClass array in your appDelegate.

In your MyClass init, get a reference to your delegate, and have it add itself to the array.

Use weak references or decrement in Deinit to avoid double counting for dirty reassignment.

This way dead instances are released rather than being retained by the array.

This way you should have a count and list of instances.

Related