NSFileManager in Foundation framework

Keywords: iOS objective-c


Ladies and gentlemen, we introduced NSMutableData in the Foundation framework in the previous chapter, and NSFileManager in the Foundation framework in this chapter.

NSFileManager is a file related class that provides methods related to file operation. Next, we will introduce how to use these methods to operate files. The files mentioned here represent our commonly used files and directories, because IOS is a Unix like operating system, and all contents in the system are l treated as files. This chapter mainly introduces operations related to directories, and later chapters will cover operations related to files.

Get home directory

@property(readonly, copy) NSURL *homeDirectoryForCurrentUser;

In Unix like systems, each user has a home directory. This method can return the home directory of the current user. However, the type of directory is NSURL. We will describe the NSURL type in detail in the following chapters.

Create directory

- (BOOL)createDirectoryAtPath:(NSString *)path
                   attributes:(NSDictionary<NSFileAttributeKey, id> *)attributes
                        error:(NSError * _Nullable *)error;

This method can create a directory. If the creation is successful, it returns YES, otherwise it returns NO. the location of the directory is in the first parameter path. The second parameter indicates whether to create a parent directory. When it is set to YES, if the parent directory of the directory in path does not exist, the parent directory will be created. When it is set to NO, if the parent directory of the directory in path does not exist, the parent directory will not be created, and the directory creation will fail. Therefore, we usually set the value of this parameter to YES.

The third parameter represents the attributes of the directory, such as read and write permissions. This is the same as the attributes of files in Unix like systems. We usually set its value to nil, indicating that the default file attributes of the system are used. The default file attribute on my system is: drwxr-xr-x. Usually, if you do not modify the default attributes of system files, the file attributes you see are the same as mine. You can try it. The fourth parameter indicates that if there is an error when creating a file, the error information will be written to this parameter. We ignore this error for the time being, so we can temporarily set it to nil

Delete directory

- (BOOL)removeItemAtPath:(NSString *)path
                   error:(NSError * _Nullable *)error;

This method can delete the specified directory. The directory is specified by the parameter path. The result of deleting the directory is determined by the return value. If the return value is YES, the directory is deleted successfully, otherwise, the directory is deleted failed. The reason for the failure can be found through the second parameter of the method, because it stores the failure information when the method fails to run. We have ignored this information for the time being.

Find out if the file exists

- (BOOL)fileExistsAtPath:(NSString *)path;

This method can judge whether the specified file (including file and directory) exists. The specified file is specified by the parameter path. If the method returns YES, it indicates that the file exists, otherwise it indicates that the file does not exist.

Usually, we'd better use this method to judge whether the directory exists before creating or deleting files, so as to avoid unnecessary errors.

Get the file name in the directory

- (NSArray<NSString *> *)contentsOfDirectoryAtPath:(NSString *)path
                                             error:(NSError * _Nullable *)error;

This method can obtain the names of all files and directories in the specified directory. The specified directory is set by the parameter path. The names of files and directories are saved into the array returned by the method. The members of the array are of NSString type, and its value is the name of text or directory. The second parameter of the method is used to store the failure information when the method fails to run. We have ignored this information for the time being.

Ladies and gentlemen, the above describes the functions and usage methods of various methods in NSFileManager class. Next, we will demonstrate how to use these methods through code. The following is the specific code:


int main()
	//Get home directory
	NSFileManager *fm = [NSFileManager defaultManager];
	NSLog(@"path: %@", [fm homeDirectoryForCurrentUser]);

	//Create a directory and judge whether it is created successfully
	NSString *path = @"/Users/talk8/test/";
	BOOL result = [fm createDirectoryAtPath:path 
		withIntermediateDirectories:YES attributes:nil error: nil];
	if(result) {
		NSLog(@"create dir successfully");
	} else {
		NSLog(@"create dir failed");

	//Delete the directory and judge whether the deletion is successful
	result = NO;
	result = [fm removeItemAtPath:path error:nil];
	if(result) {
		NSLog(@"delete dir successfully");
	} else {
		NSLog(@"delete dir failed");

	//Find out if the file exists
 	if([fm fileExistsAtPath:path]) {
		NSLog(@"file exist");
	}else {
		NSLog(@"file don't exist");

	//Get the file in the directory and display the file name
	NSArray *allFile = [fm contentsOfDirectoryAtPath:path error:nil];
	NSLog(@" %@",allFile);

	return 0;

  In the code, we added relevant comments to facilitate everyone to understand the code. There are few contents in the program. You can directly judge the running results, so we won't show the running results of the program. However, you must run the program yourself. While analyzing the code, you can compare whether the running results comply with the code logic.

Finally, we summarize the contents of this chapter:

  • 1.NSFileManager represents file related classes. It provides many methods to operate files;
  • 2. Master the methods to obtain the home directory and all files in a specific directory, which are often used in the program;
  • 3. Master the methods of creating, deleting and searching directories. It is best to find out whether the directory exists before creating and deleting directories to avoid unnecessary errors;
  • 4. The nsfilemanager class also has other methods for operating directories, such as copying and moving directories. It is recommended that you view the official documents, which are written in detail;

Ladies and gentlemen, that's all for the content of this chapter. If you want to know what will happen next, let's listen to the next chapter!

Posted by jraede on Sun, 31 Oct 2021 10:07:04 -0700