开发者

UIView.BackgroundColor leaking memory if image is used?

开发者 https://www.devze.com 2023-02-10 16:50 出处:网络
Preamble: The view controller开发者_如何转开发\'s view I\'m talking about is used in a UISplitViewController as the details view. It gets replaced if the user navigates using the UINavigationControlle

Preamble: The view controller开发者_如何转开发's view I'm talking about is used in a UISplitViewController as the details view. It gets replaced if the user navigates using the UINavigationController of the split view. When hitting "Back", a new instance of my problematic view controller is created and gets assigned to the split view controllers array of controllers. Everytime my view shows up, I see an 8MB block being allocated in Instruments. Navigating forth and back for a while will eventually crash the app.

In detail:

In my class overriding UIViewController I have a:

private UIColor oBgColor = null;

in ViewDidLoad():

    this.oBgColor = UIColor.FromPatternImage ( UIImage.FromFile ( "Data/Images/background.jpg" ) );
// This line here causes memory to go up by 8MB!
    this.View.BackgroundColor = this.oBgColor;

in ViewDidDisappear():

// These lines should sucessfully get rid of the allocated 8MB chunk.    
this.View.BackgroundColor = UIColor.Clear;
    this.oBgColor.Dispose();
    this.View.Dispose();

Code reaches ViewDidDisappear() as expected, view is gone.

The 8MB block is allocated ONLY if I assign this.oBgColor to the view's BackgroundColor. Leave that line out and all works (but I don't have a background). Each time the view gets shown, I see another 8MB getting wasted.

What's going on here? Is BackgroundImage known to be leaking?

Interesting sidenote: if I add a UIImageView as a subview and use its image instead of assign to the view BackgroundColor property, memory hardly goes up at all and gets properly released.


I wrote a sample based on your code, and while memory usage does go up when it is assigned, there is no leak (I toggled the image on and off 100 times, and memory didn't change).

The reason it goes up is the BackgroundImage property is backed by a copy @property in Objective-C, which means that the entire object is copied on assignment, so if you have a huge pattern image, and then assign it, you will for a brief period have 2 copies of the image in memory.

The reason you see the memory increase is as I explained to you on IRC, MonoTouch does not have a compacting GC in v3.

0

精彩评论

暂无评论...
验证码 换一张
取 消