Sign in Join
Wiki copytemporary

Locating the macOS tmp directory: what changed

Revision 0 to 1. Removed lines have a minus sign; added lines have a plus sign.

Title: Locating the macOS tmp directory

OldNewLine
1+*(macOS only)*
2+
3+## Overview
4+
5+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 [[Sandboxing for macOS|sandboxed]].
6+
7+You should be aware that this directory is cleaned out automatically every 3 days but otherwise persists between application launches and reboots.
8+
9+## Determining where to store files
10+
11+## Storing temporary files
12+
13+How to locate the user's unique temporary directory, display it and write a temporary file to it is demonstrated by the code below:
14+
15+``` pascal
16+...
17+{$modeswitch objectivec1}
18+
19+interface
20+
21+Uses
22+ ...
23+ CocoaAll;
24+...
25+
26+procedure TmpFile;
27+var
28+ tmpFile: TextFile;
29+ filePath: String;
30+begin
31+ ShowMessage(NSTemporaryDirectory.UTF8String);
32+
33+ filePath := NSTemporaryDirectory.Utf8String + 'test.tmp';
34+
35+ AssignFile(TmpFile, filePath);
36+ Try
37+ Rewrite(TmpFile);
38+ Writeln(TmpFile, 'This is my test tmp file.');
39+ Finally
40+ CloseFile(TmpFile);
41+ End;
42+end;
43+```
44+
45+## Why not use GetTempDir?
46+
47+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.
48+
49+## See also
50+
51+- [[Locating macOS significant directories]]
52+- [[Locating macOS app support, preferences folders]]
53+- [[Locating the macOS application resources directory]]
54+
55+---
56+*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](/wiki-contact).*

Back to history