开发者

MonoTouch and IDisposable Pattern

开发者 https://www.devze.com 2023-04-11 10:18 出处:网络
Reading MT documentation, I\'ve seen that it is possible to release memory also implementing the IDisposable .NET patt开发者_运维技巧ern.

Reading MT documentation, I've seen that it is possible to release memory also implementing the IDisposable .NET patt开发者_运维技巧ern.

For example, in a custom class that extends UIViewController (MyViewController), I could override the following method:

public override void Dispose (bool disposing)
{
   if (disposing){
     // do some stuff here
   }
   base.Dispose (disposing)
}

Starting from this point, my two questions are:

  1. What type of elements do I have to release in addition to images?
  2. Do I have to call the Dispose method from an instance of MyViewController class (myViewController.Dispose()) or the Dispose method is called automatically like dealloc method?

Thank you in advance. Regards.


First MonoTouch usage of IDisposable is identical to Mono or .NET. What you read about this subject elsewhere, on stackoverflow or on MSDN... will all apply here.

What's important wrt MonoTouch is to remember that NSObject implements IDisposable which makes a lot of sense since it represent a native object. That means that everything that inherits from NSObject, quite a large part of monotouch.dll, implements IDisposable.

  1. What type of elements do I have to release in addition to images?

Most managed NSObject-based object instances are small but they can represent large native objects (the GC will only know about the first, managed, size).

So it's best to Dispose NSObject-based instances when you can, e.g. when you're using them as local variables. The using pattern makes it easy to do so in C#.

OTOH use your judgment, a small NSString won't take much memory, while others could be large (or unknown, e.g. NSString GetWebPageContent (NSUrl).

  1. Do I have to call the Dispose method from an instance of MyViewController class (myViewController.Dispose()) or the Dispose method is called automatically like dealloc method?

Part of the Dispose pattern ensure that the finalizer will call Dispose if it has not been called previously. As such the GC will, eventually, reclaim the memory (both managed and unmanaged/native) associated with those instances.

You might want to use some tools, like Gendarme (which will run on OSX) or FxCop (Windows-only) that will report to you (for example) if some of your types have IDisposable fields that are not disposed properly.

Disclaimer : I'm Gendarme's maintainer :-)

0

精彩评论

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

关注公众号