How to clear abandoned memory that doesn't point to own code?

后端 未结 3 1352
无人共我
无人共我 2021-01-22 20:25

It seems that my app is abandoning memory since the persistent memory of recorded heapshots don\'t fall to zero and the heap continue to grow when the same set of operations are

3条回答
  •  南方客
    南方客 (楼主)
    2021-01-22 20:47

    I think you need to look explicitly for retain cycles. When in hierarchy you have a parent object object that has related object and both have strong type of proprties, they will never get released from memory.

    Quick example:

    @interface Parent : NSObject
    @property (strong) Child *child;
    @end
    @interface Child : NSObject
    @property (strong) Parent *parent;
    @end
    

    Also by default properties are strong, so it is the same if you do not declare it at all.

    The way it should be:

    @interface Parent : NSObject
    @property (strong) Child *child;
    @end
    @interface Child : NSObject
    @property (weak) Parent *parent;
    @end
    

    I also found information that Instruments can show you retain cycles (and it looks nice). More details here How to activate Cycles reporting in Instruments under ARC? However I don't know if it works with ARC, comments may suggest it does not. As a cumbersome way I can recommend commenting out some code you feel may be responsible and then check the picture.


    So that's for the retain cycles. Another thing you should look for is when you allocate memory that ARC is not able to return. Those calls are looking like C functions and by convention have a word Create in the name. Each time you make such a pointer then you should also clean after yourself. Just to give you some examples:

    • CGColorCreate - CGColorRelease
    • CGColorSpaceCreateWithName - CGColorSpaceRelease
    • CGBitmapContextCreate - CGContextRelease

    As you can see each function has it's corresponding releasing function which usually you should be able to find in documentation.

提交回复
热议问题