Wiki copymirror

This is a mirror of the wiki at pascal.chat. Editing, history and sign-in are there.

Locating the macOS tmp directory

(macOS only)

Overview

To locate the current user's temporary directory in macOS you should use the native macOS Foundation function NSTemporaryDirectory(). This directory is unique for each user, the user is guaranteed to have write permissions to it, and it is in a hashed location which is not predictable in advance so that it is safe from security issues associated with predictable locations. It is also guaranteed to work when your application has been sandboxed.

You should be aware that this directory is cleaned out automatically every 3 days but otherwise persists between application launches and reboots.

Determining where to store files

Storing temporary files

How to locate the user's unique temporary directory, display it and write a temporary file to it is demonstrated by the code below:

pascal
...
{$modeswitch objectivec1} 

interface

Uses
  ...
  CocoaAll;
...

procedure TmpFile;
var
  tmpFile: TextFile;
  filePath: String;
begin
  ShowMessage(NSTemporaryDirectory.UTF8String);

  filePath := NSTemporaryDirectory.Utf8String + 'test.tmp';

  AssignFile(TmpFile, filePath);
  Try
    Rewrite(TmpFile);
    Writeln(TmpFile, 'This is my test tmp file.');
  Finally
    CloseFile(TmpFile);
  End;
end;

Why not use GetTempDir?

It should be noted that Free Pascal's GetTempDir function (from SysUtils) uses the value of the macOS TMPDIR environment variable to determine the path to where the current user's temporary files should be stored. This is a possible security issue because the TMPDIR environment variable is easily compromised.

See also


From the Free Pascal wiki, page "Locating the macOS tmp directory", as it stood on 2021-03-26 after a change by Trev, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's Licensing page. If you have concerns about this material, message the admin.

Revision 1, last changed by WikiArchive .