1

What is the best/safest way to free objects from memory in units in a Delphi Firemonkey Multi Device project?

Which of the following do I use or maybe somethings else?

  1. FreeAndNil(object);
  2. object.free;
    object := nil;
  3. object.DisposeOf
    object := nil;

Or maybe something with 'FreeInstance' or 'CleanupInstance'

BTW I know that for Forms the best way is to use the 'OnClose' event and then call:

Action := TCloseAction.caFree;

I only want to know how to free the memory for my own object classes.

Remi
  • 1,289
  • 1
  • 18
  • 52
  • `obj.Release` for visual objects. For others - use your first or second method, because DisposeOf is not safe due to ARC. I can't find "canonical" answer, but I know, that it exist on SO – kami Dec 15 '16 at 15:14
  • 3
    The documentation covers this in [Automatic Reference Counting in Delphi Mobile Compilers](http://docwiki.embarcadero.com/RADStudio/Berlin/en/Automatic_Reference_Counting_in_Delphi_Mobile_Compilers#The_Free_and_DisposeOf_methods_under_ARC) – Ken White Dec 15 '16 at 16:21
  • @Remi: on mobile, object lifetimes are managed by ARC, so `Free()` is silently translated by the compiler to `:= nil` to decrement the object's reference count. `FreeAndNil(object)` and `objct.Free; object := nil` do the same thing whether ARC is used or not. `DisposeOf()` forces the object to be destroyed immediately (destructor is called) even if there are still outstanding references to the object. Those references must still be cleared eventually to release allocated memory. – Remy Lebeau Dec 15 '16 at 19:31
  • 1
    @kami: "*DisposeOf is not safe due to ARC*" - that is misleading. `DisposeOf()` exists *because of* ARC, and it works fine. You just have to understand HOW it works to use it correctly/effectively. – Remy Lebeau Dec 15 '16 at 19:31
  • 2
    As far as TComponent descendants are concerned you should use DisposeOf - see [How to free a component in Android / iOS](http://stackoverflow.com/questions/27818697/how-to-free-a-component-in-android-ios) – Dalija Prasnikar Dec 15 '16 at 19:58
  • @RemyLebeau I know, how it works. "Zombie object state" - bad thing. – kami Dec 15 '16 at 20:30
  • 1
    @kami: No, *zombie object state* is not necessarily bad. It's clear you don't understand the topic or how ARC works. You should read the link I posted thoroughly. ARC is how interfaces have worked in Delphi and COM for decades. It is also used extensively in the .NET framework. – Ken White Dec 15 '16 at 23:22

0 Answers0