How To: Self-Deleting FolderItem

I’m probably late to this party, but since this just occurred to me…

There are times when you might need a file that goes away automatically. For example, you might set up a flag file that should be deleted when your app quits properly (if the file is there when the app starts up, you know that the app had crashed on a previous run, for example). Or perhaps you want to set up a temporary file that goes away when no longer needed.

The answer is a self-deleting FolderItem. Make a subclass of the FolderItem (SelfDeletingFolderItem), and then add a Destructor:

Protected Sub Destructor()
  if me.Exists then
  end if
End Sub

You can also add an Operator_Convert to make it easy to convert from an ordinary FolderItem:

Protected Sub Operator_Convert(f As FolderItem)
  me.Constructor( f )
End Sub

Now you can do things like:

dim f as SelfDeletingFolderItem = GetTemporaryFolderItem()
myObj.TempFile = f
// Create and use the TempFile

As soon as myObj goes out of scope, TempFile goes away by itself. (There is a design principle behind this whose name escapes me at the moment.) You can get fancier (and more dangerous), of course, and make sure that, if the FolderItem is actually a Directory, its contents get deleted too, but I’ll leave that as an exercise for the reader.

I hope this helps someone.

Right, this is what I had been suggesting to Greg O’Lone recently (but I believe he didn’t understand me). I use this myself often. Thought about blogging this tip, too. Now you’ve done it! :slight_smile:

It’s similar to my tip for Debugging - using the fact that Xojo destructs objects immediately when they stop being referenced.

Lots of other tricks can be achieved with this, e.g. I use a class that increments a “busy” counter in its constructor and decrements it in its destructor, along with executing some operation when it goes back to zero, and then construct this object inside operations that need some blocking feature (e.g. show a busy cursor), so that I can make sure that the busy cursor is reset to a normal cursor when my code is finished, even when it’s stopped with an exception. It’s all about thinking where one wants to have some operation executed once you let go of something you hold temporarily.