How to find where an Objective-C object is referencing?

I use the Allocations tool in Xcode to track a created but not released object. I can see an increase in the number of objects as the code executes, and I see where the objects are created using the call stack, but I cannot determine where the references to the objects are stored. I think that they are kept in a third-party library, but the developer says "no, it should be your code." I set the links in my code to zero, but the objects remain.

+4
source share
2 answers

I don’t think there is a tool that will tell you where each link is at any given time. Since you use ARC, in my experience, there are two fairly common ways to force yourself to catch the reference loop and memory leak:

  • Class A has a strong reference to an instance of class B, which has a strong reference to the same instance of class A.
  • Blocks implicitly store references to objects that it captures. Thus, one obvious problem is that your object stores a block that stores a reference to itself.

Example:

self.retainedBlock = ^{ [self doSomething]; }; 

Fix:

 __weak id weakSelf = self; self.retainedBlock = ^{ id strongSelf = weakSelf; [strongSelf doSomething]; }; 
+1
source

This is desperation, but you can do it:

  • disable ARC for the affected object (or bypass it, see below);
  • add retain , autorelease and release
  • Track saved items with saved save.

The simplest example:

 - (void)release { NSLog(@"%@ : %@", self, [NSThread callStackSymbols]); [super release]; } 

(although in practice, it is probably much smarter to store the [NSThread callStackSymbols] array for memory management calls in a dictionary indexed, for example, [NSValue valueWithPointer:self] , then to access it either with lldb or by writing it to disk, why need to manually index data efficiently?)

Probably the easiest way to work with ARC is to write one class with ARC disabled, which can handle log memory management methods for the objects you want to track.

-1
source

All Articles