قالب وردپرس درنا توس
Home / IOS Development / Temporary Files – NSHipster

Temporary Files – NSHipster



Volumes are written about persistent data,
but when it comes to short-term temporary files,
There is very little to go for cocoa.
(Or if it has, maybe it was poetic ephemeral itself).


Temporary files are used to write data to disk
before you either move it to a fixed location
or throw it away.
For example, when a movie editor exports a project,
It can write each frame to a temporary file until it reaches the end
and moves the finished file to the directory ~ / Movies .
Use a temporary file for such situations
ensure that the tasks are completed atomic
(whether you get a finished product or nothing at all, nothing halfway),
and without creating too much memory pressure on the system
(On most computers, disk space is ample while memory is limited).

There are four different steps to work with a temporary file:

  • Create a temporary directory in the file system
  • Create a temporary file in the directory with a unique filename
  • Write data to the temporary file
  • Move or delete the temporary file when done

Create a temporary directory

The first step to create a temporary file
is finding a reasonable, out-of-the-way placement that you can write ̵

1;
a place that is unclear it does not
get in the way of the user
or be retrieved by a system process like
Spotlight Indexing, Time Machine Backup, or iCloud Sync.

In Unix Systems, the directory / tmp is the de facto scratch rate.
However, today's macOS and iOS apps run in a container
and do not have access to system directories;
a hard-coded path as it will not cut it.

Instead, let us ask File Manager to point us in the right direction

let temporaryDirectoryURL =
try FileManager .
19659018] standard url ( for . itemReplacementDirectory
in : .. ] userDomainMask
appropriateFor : URL ( fileURLWithPath : "/" ),
sheep : true )

  NSFileManagers    *   File    =    [  NSFileManagers    defaultManager ]; 
  NSError    *   Error    =    nil ; 
  NSURL    *   temporaryDirectoryURL    = 
      [       URLForDirectory :   NSItemReplacementDirectory  inDomain :   NSUserDomainMask [19659070] NSUserDomainMask [19659070] ]  :      NSURL    fileURLWithPath :   @ "/" ] 
                            19659017]: &   error ]; 

Parameters of this method are often misunderstood,
so let's go through each other to understand what this method really does:

  • We ship the password for the replacement search path ( .item Replacement Directory )
    to say that we are interested in a temporary catalog.
  • We send the user domain mask ( .user Domain Mask )
    to get a directory that is available to the user.
  • For appropriate for the URL parameter,
    The only part of the file address being considered is the volume;
    Therefore, we may send URL (file URLWith Path: "/")
    to specify the current volume.
  • Finally, we send true to the create parameter
    to save us the extra step of creating it ourselves.

The resulting directory will have a path that looks something like this:
file: /// var / folders / l3 / kyksr35977d8nfl1mhw6l_c00000gn / T / TemporaryItems / (A% 20Document% 20Being% 20Saved% 20By% 20NSHipster% 208) /

Create a temporary file

With a place to call home (at least temporarily)
The next step is to find out what to call our temporary file.
We are not picky about what it should be called –
just as long as it's unique,
and does not interfere with other temporary files in the directory.

The best way to generate a unique identifier
is Process Info property globally Unique String :

  ProcessInfo   () .   globallyUniqueString 
 

  

  

    

     NSProcessInfo    processInfo ]    globallyUniqueString ]; 

The resulting file name will look like this:
42BC63F7-E79E-4E41-8E0D-B72B049E9254-25121-000144AB9F08C9C1

Alternatively,
UUID

] UUID ] UUIDString ]

A generated UUID string has the following format:
B49C292E-573D-4F5B-A362-3F2291A786E7

Now that we have an appropriate directory and unique file name,
let's add them together to create our temporary file:

  la    temporaryDirectoryURL    = 
      try    FileManager .   standard .   url     to :      itemReplacementDirectory  
                                  in .      userDomainMask  
                                  appropriateFor . 
                                   [ ]   :    "/" ), 
                                   :    sant )    la    temporaryFileName [19659014] =    ProcessInfo   () .   globallyUniqueString 

  la    temporaryFileURL    = 
      temporaryDirectoryURL .   appendingPathComponent   ([19659025] temporaryFileName ) 

  NSFileManagers    *   File    =    [  NSFileManagers    defaultManager ]; 

  NSError    *   Error    =    nil ; 
  NSURL    *   temporaryDirectoryURL    = 
      [       URLForDirectory :   NSItemReplacementDirectory  inDomain :   NSUserDomainMask 
      NSUserDomainMask 
      ]  :      NSURL    fileURLWithPath :   @ "/" ] 
                            19659017]: &   Error ]; 

  NSString    *   temporaryFileName    = 
      [  NSProcessInfo    processInfo ]    globallyUniqueString ]; 
  NSURL    *   temporaryFileURL    = 
      [  temporaryDirectoryURL 
          URLByAppendingPathComponent :   temporaryFileName ]; 

Writing to a Temporary File

The only action to create a file address does not matter to the file system;
A file is created only when the file path is written.
So let's talk about our possibilities to do it:

Write data to a URL

The easiest way to write data to a file

data data data data data . 19659017] write ( to : temporaryFileURL
                alternatives . atomicWrite )

  NSData    *   data ; 
  NSError    *   Error    =    nil ; 
  [  data    writeToURL [19659021]:   error     error ]; 

By sending atom ] Enter the option,
We make sure all the data is written
or the method returns an error.

Write data to a file manager

If you do something more complicated
than to write a single Data object to a file,
consider file Handle instead: :. temporaryFileURL )
postpone {.

]

() }

filehandle write ( data )

  NSError    *   error    =    nil ; 
  NSFileHandle    *   filehandle [19659014] = 
      [  NSFileHandle    fileHandleForWritingToURL :   temporaryFileURL 
                                  Error :  &   ] error ]; 
  [  fileHandle    writeData :   data ]; 

  [  fileHandle    closeFile ]; 

Write data to an output current

For more advanced APIs,
it's not uncommon to use Output Stream
to control the data flow.
Create an output stream for a temporary file
is no different than any other type of file:

  la    outputStream    = 
      OutputStream   (  url :    temporaryFileURL     append [19659021!] ]:    sanne )  
  postpone    {.    outputstream    close   ()  } 

  data [19659017].   withUnsafeBytes    {   bytes    in 
      outputstream . 

bytes maxLength :. bytes telle ) }

  NSOutputStream    *   outputStream    = 
      [  NSOutputStream    outputStreamWithURL [19659021]:   temporaryFileURL 
                                   voye :   JA ]; 

  [  outputstream    write :   data   [19659025] bytes 
            maxLength .   data     length h ]; 

  [  outputstream    close ]; 

Move or delete temporary file

Files in system-designated temporary directories
is periodically deleted by the operating system.
So if you intend to hold onto the file you have written for,
You must move it somewhere outside the fire line.

If you already know where the file is going to live,
You can use File Manager to move it to its permanent home:

  la    fileURL :    URL 
  try    FileManager  . 

standard moveItem ( at : temporaryFileURL                                   to : fileURL ). [19659163] NSFileManagers * File = [ NSFileManagers defaultManager ]; NSURL * fileURL ; NSError * Error = nil ; [ error : error : temporaryFileURL toURL : [19659025] fileURL error error ];

Although the system eventually stores files in temporary directories,
It's not a bad idea to be a responsible citizen
and follow the guidance of
"Take photos only, just give footsteps."

File Manager can also help us here,
with remove at : temporaryFileURL )

  NSFileManagers    *   File    =    [  NSFileManagers    defaultManager ]; 

  NSError    *   Error    =    nil ;   [ ]    removeItemAtURL :   temporaryFileURL 
                         error : [19659017] And   error ]; 


"This shall also pass"
is a mantra acknowledging that all things are actually temporary.

Within the scope of the application's life cycle,
Some things are more temporary than others,
and it is with the knowledge that we choose to act appropriately:
seeking to find the right place,
make a unique impact,
and go without traces.

Perhaps we can learn something from this cycle in our own,
short and brilliant life cycle.


Source link

Share