Difference between checking file existence with NSData or NSFileManager

I am trying to check if a file exists. If I use this:

NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]]; if (data == NULL){ ... } 

I always get NULL .

Than I found NSFileManager :

 NSFileManager *fileManager = [NSFileManager defaultManager]; if (![fileManager fileExistsAtPath:filePath]) 

It works as I expect. What makes the difference between the two procedures?

+4
source share
3 answers

What file path do you pass to URLWithString? If this is a normal path (does not start with file: // ....), you should use fileURLWithPath: to convert the path of the string to a URL.

+3
source

The two classes are only slightly related. The first function you use is the convenience method, which almost certainly uses the NSFileManager in the background. Otherwise, however, NSData has many purposes not related to files.

Which of the two you use depends on your intentions. If you want to read the contents of a file, you are likely to use the first one. If you want to delete the file, if it exists, you will definitely use the second one.

+2
source

NSData deals with content (or data), maybe a file. Maybe not.

NSFileManager processes the file in the file system, for example, the path to the file, copies / moves, lists the folder, checks permission, etc. This has more to do with file abstraction than with file content.

0
source

All Articles