Time: Tuesday, 06 June 2017
Note: Part of the content of this article is from Mucho.com. @ Mu Course Net: http://www.imooc.com
Teaching sample source code: none
Personal learning source code: https://github.com/zccodere/s...
Chapter 1: Learning Guide
1-1 Learning Guide
Application requirements
Learning objectives
1. Application scenarios for file reading and writing 2. Understanding the file storage mechanism of iOS 3. Develop with basic document reading and writing
Chapter 2: Introduction of Sandbox
Introduction of 2-1 Sandbox
Schematic diagram of sandbox mechanism
Applications can only access files in their application directory.
sand box
1.Documents: File data generated by program creation or application browsing 2.Library: The default settings or status information of the program is stored in this directory 3.tmp: Provides a place for instant creation of temporary files without persistence
File catalog schematic
Path Processing
1. Sandbox Path Processing 2. Processing of NSString Class Path Function 3. About NSData
2-2 Gets Documents Path
Code demonstration:
// The Path to Get Sandbox - (NSString *)getHomePath{ NSString *homePath = NSHomeDirectory(); NSLog(@"HomePath = %@",homePath); return homePath; } // Get the Documents path - (NSString *)getDocumentsPath{ // Retrieving the specified path in the application // First parameter: search path name // Second parameter: confined to sandbox NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentPath = [docPaths lastObject]; NSLog(@"DocumentPath = %@",documentPath); return documentPath; }
2-3 Gets Library and Tmp Paths
Code demonstration:
// Get the Library path - (NSString *)getLibraryPath{ NSArray *libPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryPath = [libPaths firstObject]; NSLog(@"LibraryPath = %@",libraryPath); return libraryPath; } // Get the Tmp path - (NSString *)getTmpPath{ NSString *tmpPath = NSTemporaryDirectory(); NSLog(@"TmpPath = %@",tmpPath); return tmpPath; }
Chapter Three: Data Conversion
Processing of Path Function of 3-1 NSString Class
Code demonstration:
// Processing of Path Function of NSString Class - (void)parsePath { NSString *path = @"/data/Containers/Data/Application/test.png"; // Getting the components of the path NSArray *array = [path pathComponents]; NSLog(@"PathComponents = %@",array); // Extract the last component of the path NSString *name = [path lastPathComponent]; NSLog(@"FileName = %@",name); // Delete the last part of the path NSString *string = [path stringByDeletingLastPathComponent]; NSLog(@"LastPath = %@",string); // Add name.txt NSString *addString = [string stringByAppendingPathComponent:@"name.txt"]; NSLog(@"AddString = %@",addString); }
3-2 NSData Data Data Conversion
Code demonstration:
// NSData Data Data Conversion - (void) dataChange:(NSData *)data { // NSData -> NSString NSString *aString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // NSString -> NSData NSData *aData = [aString dataUsingEncoding:NSUTF8StringEncoding]; // NSData -> UIImage UIImage *image = [UIImage imageWithData:aData]; // UIImage -> NSData NSData *data2 = UIImagePNGRepresentation(image); NSLog(@"%@",data2); }
Chapter IV: Detailed Document Operation
4-1 Create folders using NSFileManager
File operation function
1. The NSFileHandle class mainly reads and writes the contents of files. 2. The NSFileManager class mainly operates on files (deletion, creation, etc.)
Code demonstration:
// create folder - (void)createFolder { NSString *docPath = [self getDocumentsPath]; NSString *testPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSFileManager *manager = [NSFileManager defaultManager]; // With Intermediate Directories YES Can Overlay NO Can't Overlay BOOL result = [manager createDirectoryAtPath:testPath withIntermediateDirectories:YES attributes:nil error:nil]; if (result) { NSLog(@"Folder Creation Successful"); } else{ NSLog(@"Folder creation failed"); } } // create a file - (void)createFile { NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"My Notes.txt"]; NSFileManager *manager = [NSFileManager defaultManager]; BOOL result = [manager createFileAtPath:filePath contents:nil attributes:nil]; if (result) { NSLog(@"File Creation Successful"); } else{ NSLog(@"File creation failed"); } }
4-2 Write to File
Code demonstration:
// write file - (void)writeFile { NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"My Notes.txt"]; NSString *content = @"Test Note Writing"; BOOL result = [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil]; if (result) { NSLog(@"File Writing Successful"); } else{ NSLog(@"File Writing Failure"); } }
4-3 Additional File Content
Code demonstration:
// Additional document content - (void) addFileContent{ NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"My Notes.txt"]; // Open the file and prepare for updates NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; // Jump the node to the end of the file [fileHandle seekToEndOfFile]; NSString *addContent = @"This is what I want to add."; NSData *addContentData = [addContent dataUsingEncoding:NSUTF8StringEncoding]; // Write data [fileHandle writeData:addContentData]; // Close files [fileHandle closeFile]; }
4-4 Delete Files
Code demonstration:
// Determine whether the specified file exists - (BOOL)fileExist:(NSString *)filePath{ NSFileManager *manager = [NSFileManager defaultManager]; if([manager fileExistsAtPath:filePath]){ return YES; } return NO; } // Delete files - (void)removeFile{ NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"My Notes.txt"]; NSFileManager *manager = [NSFileManager defaultManager]; BOOL isExist = [self fileExist:filePath]; if(isExist){ BOOL result = [manager removeItemAtPath:filePath error:nil]; if (result) { NSLog(@"Successful deletion of files"); }else{ NSLog(@"File deletion failed"); } }else{ NSLog(@"The file does not exist. File path = %@",filePath); return; } }
Chapter V: Explanation of Examples
5-1 instance operation
Examples
1. Get pictures and store them in a local folder 2. Read pictures of local designated folders for display [after-class exercises]
Code demonstration:
// Write pictures - (void)writeImage{ UIImage *testImage = [UIImage imageNamed:@"1.jpg"]; NSData *imageData = UIImagePNGRepresentation(testImage); NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"picture"]; [imageData writeToFile:filePath atomically:YES]; }
Chapter Six: Summary of Courses
6-1 Course Summary
Course Review
Application scenarios sand box Path Processing Examples of file processing
Complete code for this course
// // ViewController.m // MyPathFunc // // Created by zc on 2017/6/6. // Copyright 2017 com.zccoder. All rights reserved. // #import "ViewController.h" @interface ViewController () @end @implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view, typically from a nib. // [self getHomePath]; // [self getDocumentsPath]; // [self getLibraryPath]; // [self getTmpPath]; // [self parsePath]; // [self createFolder]; // [self createFile]; // [self writeFile]; // [self addFileContent]; // [self removeFile]; [self writeImage]; } // The Path to Get Sandbox - (NSString *)getHomePath{ NSString *homePath = NSHomeDirectory(); NSLog(@"HomePath = %@",homePath); return homePath; } // Get the Documents path - (NSString *)getDocumentsPath{ // Retrieving the specified path in the application // First parameter: search path name // Second parameter: confined to sandbox NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentPath = [docPaths lastObject]; NSLog(@"DocumentPath = %@",documentPath); return documentPath; } // Get the Library path - (NSString *)getLibraryPath{ NSArray *libPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES); NSString *libraryPath = [libPaths firstObject]; NSLog(@"LibraryPath = %@",libraryPath); return libraryPath; } // Get the Tmp path - (NSString *)getTmpPath{ NSString *tmpPath = NSTemporaryDirectory(); NSLog(@"TmpPath = %@",tmpPath); return tmpPath; } // Processing of Path Function of NSString Class - (void)parsePath { NSString *path = @"/data/Containers/Data/Application/test.png"; // Getting the components of the path NSArray *array = [path pathComponents]; NSLog(@"PathComponents = %@",array); // Extract the last component of the path NSString *name = [path lastPathComponent]; NSLog(@"FileName = %@",name); // Delete the last part of the path NSString *string = [path stringByDeletingLastPathComponent]; NSLog(@"LastPath = %@",string); // Add name.txt NSString *addString = [string stringByAppendingPathComponent:@"name.txt"]; NSLog(@"AddString = %@",addString); } // NSData Data Data Conversion - (void) dataChange:(NSData *)data { // NSData -> NSString NSString *aString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; // NSString -> NSData NSData *aData = [aString dataUsingEncoding:NSUTF8StringEncoding]; // NSData -> UIImage UIImage *image = [UIImage imageWithData:aData]; // UIImage -> NSData NSData *data2 = UIImagePNGRepresentation(image); NSLog(@"%@",data2); } // create folder - (void)createFolder { NSString *docPath = [self getDocumentsPath]; NSString *testPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSFileManager *manager = [NSFileManager defaultManager]; // With Intermediate Directories YES Can Overlay NO Can't Overlay BOOL result = [manager createDirectoryAtPath:testPath withIntermediateDirectories:YES attributes:nil error:nil]; if (result) { NSLog(@"Folder Creation Successful"); } else{ NSLog(@"Folder creation failed"); } } // create a file - (void)createFile { NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"My Notes.txt"]; NSFileManager *manager = [NSFileManager defaultManager]; BOOL result = [manager createFileAtPath:filePath contents:nil attributes:nil]; if (result) { NSLog(@"File Creation Successful"); } else{ NSLog(@"File creation failed"); } } // write file - (void)writeFile { NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"My Notes.txt"]; NSString *content = @"Test Note Writing"; BOOL result = [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil]; if (result) { NSLog(@"File Writing Successful"); } else{ NSLog(@"File Writing Failure"); } } // Determine whether the specified file exists - (BOOL)fileExist:(NSString *)filePath{ NSFileManager *manager = [NSFileManager defaultManager]; if([manager fileExistsAtPath:filePath]){ return YES; } return NO; } // Additional document content - (void) addFileContent{ NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"My Notes.txt"]; // Open the file and prepare for updates NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath]; // Jump the node to the end of the file [fileHandle seekToEndOfFile]; NSString *addContent = @"This is what I want to add."; NSData *addContentData = [addContent dataUsingEncoding:NSUTF8StringEncoding]; // Write data [fileHandle writeData:addContentData]; // Close files [fileHandle closeFile]; } // Delete files - (void)removeFile{ NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"My Notes.txt"]; NSFileManager *manager = [NSFileManager defaultManager]; BOOL isExist = [self fileExist:filePath]; if(isExist){ BOOL result = [manager removeItemAtPath:filePath error:nil]; if (result) { NSLog(@"Successful deletion of files"); }else{ NSLog(@"File deletion failed"); } }else{ NSLog(@"The file does not exist. File path = %@",filePath); return; } } // Write pictures - (void)writeImage{ UIImage *testImage = [UIImage imageNamed:@"1.jpg"]; NSData *imageData = UIImagePNGRepresentation(testImage); NSString *docPath = [self getDocumentsPath]; NSString *dirPath = [docPath stringByAppendingPathComponent:@"Mu Course Net"]; NSString *filePath = [dirPath stringByAppendingPathComponent:@"picture"]; [imageData writeToFile:filePath atomically:YES]; } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end