Not sure if it's a memory leak (ARC)

2019-08-31 08:18发布

问题:

I'm writing custom animations and I suspect that I have a memory leak, but I'm not sure. Every time I run a given animation memory goes up a little, but it doesn't go down. To make sure, I made a test:

NSLog(@"%@", self.weakanim);

// The animation collection to run
HyAnimationCollection * collection = [[HyAnimationCollection alloc] init];

self.weakanim = collection;

First this logs nil then it always logs an address. So there are two indicators here:

  1. Memory starts at 9.7MB and goes up 0.1MB every 10 runs of the animation. I tested this to about 12MB. Now, should the memory be freed every time or is it just that ARC (like, say, JVM's garbage collector) only releases memory periodically? That is, maybe it isn't a leak, but instead ARC has not released it yet because I didn't reach a certain amount.
  2. I declared weakanim as weak just to see if the previous animation collection was being released, but the same issue still arises: is ARC not releasing yet?

回答1:

  1. ARC doesn't work like a JVM. The closest you get is when it uses the "autorelease pool." In this case, objects won't be related until the end of the run loop. If you can see the animation running then the run loop is most likely running and the pool should be flushed periodically.

  2. A better way of showing whether there's a leak would be to put a breakpoint in the dealloc method of your HyAnimationCollection class. If the rest of your investigation is correct, my guess is that it's never called. You probably have a retain cycle in that code.