Reading MT documentation, I’ve seen that it is possible to release memory also implementing the IDisposable .NET pattern.
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:
- What type of elements do I have to release in addition to images?
- 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
NSObjectimplementsIDisposablewhich makes a lot of sense since it represent a native object. That means that everything that inherits fromNSObject, quite a large part of monotouch.dll, implementsIDisposable.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
usingpattern makes it easy to do so in C#.OTOH use your judgment, a small
NSStringwon’t take much memory, while others could be large (or unknown, e.g.NSString GetWebPageContent (NSUrl).Part of the
Disposepattern ensure that the finalizer will callDisposeif 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 🙂