Sometimes we need to deal with temporary FolderItem instances, and in those cases it would be great to not have to care about when they get out of scope in order to delete them. Wouldn’t it be great to automate that task? Continue reading and you’ll see how easy it is to implement this!
In order to instruct a FolderItem to delete itself when it’s out of scope, we will create a new class that will act as a wrapper for the FolderItem, making use of the Operator_Convert method, so we can assign a FolderItem to it and also get the underlying FolderItem wrapped in it.
So, go ahead and create a new Class. We can name it as TempFolderItem with an empty Super class in the Inspector Panel.
Add a new property to the new TempFolderItem class, using the following values in the Inspector Panel:
- Name: mFile
- Type: FolderItem
- Scope: Protected
Next, let’s add a Constructor method to our class with the following signature:
- Name: Constructor
- Parameters: f As FolderItem
- Scope: Public
And simply put this line of code in the associated Code Editor:
mFile = f
Then, we need to add a couple of Operator_Convert methods:
- Name: Operator_Convert
- Parameters: f As FolderItem
- Scope: Public
- Code Editor: mFile = f
- Name: Operator_Convert
- Returned Type: FolderItem
- Scope: Public
- Code Editor: Return mFile
Finally, we will add the Destructor method. This one will be in charge of deleting the underlaying FolderItem once the class instance is out of scope:
- Name: Destructor
- Scope: Public
- Code Editor:
Try
  If mfile <> Nil And mfile.Exists And mfile.IsWriteable Then
    If Not mFile.IsFolder Then
    mfile.Remove
  End
End If
Catch e As IOException
  Raise e
End Try
Temporary FolderItems in Practice
That’s all – our class definition is done! In order to test it, create a Desktop project, add the Open Event Handler to the default window and write this snippet of code in the Code Editor:
Const textContent As String = "Lorem ipsum dolor sit amet, consectetur adipiscing elit"
f = New TempFolderItem(specialfolder.desktop.child("Test.txt"))
Try
  Var tos As TextOutputStream = TextOutputStream.Open(f)
  tos.WriteLine textContent
  tos.Close
Catch e As IOException
  MessageBox(e.Message)
End Try
Next add a new Property to the default window (Window1) using the following values in the Panel Inspector:
- Property Name: f
- Type: TempFolderItem
- Scope: Public
This way, the TempFolderItem will be in Scope (this is, in memory) while the Window1 window remains opened. Once we close the window, everything will be destroyed from memory, including this property. Also the underlying FolderItem stored on it via the Destructor method of our class will be deleted.
Run the example project and see how it works. While the Window1 window remains open, our file will be available in the Desktop; but as soon we close the Window1 window… the file will be deleted automatically!
Questions? Ask me about Xojo programming on Twitter @XojoES or on the Xojo Forum.
