sanjihan
sanjihan

Reputation: 6004

Where do files go when you delete them programatically with swift?

Where do files go when you delete them programatically? I deleted them with this code, but the Trash for today is empty. Is it possible to retrieve them?

let filemgr = NSFileManager.defaultManager()
        do{
            let filelist = try filemgr.contentsOfDirectoryAtPath(fontFolderPath)
            for filename in filelist {
                do{ try filemgr.removeItemAtPath(fontFolderPath+filename)} catch{}
            }
        }catch{}

Upvotes: 2

Views: 1318

Answers (3)

Grady Player
Grady Player

Reputation: 14549

basically unixy systems manage files the same way, there is a ref count, that is the number of hard links + times the file is open... So you can rm an open file, and the file will still exist, you can write to it, and read from it, with a valid file descriptor or FILE * stream object, then when it is closed the file will actually be removed from the disk...

int fd = open("somefile", O_RDWR);
unlink("somefile"); // removes somefile from the directory listing, but not disk
write(fd, "hello", 5);
lseek(fd,0,SEEK_SET); // seek to start of file 
char buffer[6] = {0};
read(fd,buffer,5); // reads in "hello"
close(fd); // last reference removed, file is removed.

if you want to move a file to the Trash, that is a different operation and specific to OS X and iOS

Upvotes: 1

vadian
vadian

Reputation: 285064

Using the URL related API of NSFileManager you have two options:

  • func removeItemAtURL(_ URL: NSURL) throws

    deletes the item immediately like /bin/rm in Terminal.app and has the same functionality as removeItemAtPath.

  • func trashItemAtURL(_ url: NSURL, resultingItemURL outResultingURL: AutoreleasingUnsafeMutablePointer<NSURL?>) throws

    moves the item to the trash folder returning the item’s location in the trash via the inout pointer.

Upvotes: 4

Matt Long
Matt Long

Reputation: 24466

The removeItemAtPath method deletes them. They're gone. If you want to move something to the trash, you need to use NSWorkSpace. You can see an example of moving an entire directory to the trash here: Move directory to trash

Upvotes: 2

Related Questions