Understanding Instruments memory allocation log on iOS

前端 未结 4 1005
孤独总比滥情好
孤独总比滥情好 2021-02-04 14:21

I have built an iOS app that is almost done, however, I have recently experienced that it crashes after while due to \"Memory pressure\". So I started profiling the memory alloc

4条回答
  •  一整个雨季
    2021-02-04 15:09

    Here's how I debug these.

    1. In Instruments, use the Allocations instrument and turn on "Record reference counts"

    enter image description here

    1. Run your app to a "steady state", including performing the operation you think is leaking a few times.

    2. In Instruments, set your baseline memory level using the in/out markers.

    3. Perform the operation you think is leaking a few times. (say 7)

    4. In Instruments, switch to the view that shows all allocations and look for objects that have been allocated yet not deallocated the same number of times as the operation you just performed (again maybe 7 times). You'll first want to try to find an object specific to your program... So prefer MyNetworkOperation instances instead of generic foundation classes like NSData. click arrow next to class you are interested in click arrow next to an allocated object

    5. Select one of the objects that hasn't been deallocated and look at it's allocation history. You'll be able to see the call stack for every alloc/retain/release/autorelease for the object in question.. Probably one of the calls will look suspicious to you. history of retain/release for selected object

    I suppose these steps apply more in a non-ARC environment. Under ARC you might be looking for something that's a retain cycle.

    In general you can avoid retain cycles by making sure your strong references only go in one direction... For example, a view has strong references to it's subviews and each subview must only ever use weak references to refer to any parent view. Or perhaps your view controller has a strong reference to your view. Your view must only have a weak reference to its view controller. Another way to say this is to decide in each relationship which object "owns" the other.

提交回复
热议问题