Moocnet_ Learning summary of “IOS basic course – file operation”

Time:2020-8-10

Time: Tuesday, June 6, 2017
Note: part of this article is from moocnet. @Moocnet: http://www.imooc.com
Teaching example source code: None
Personal learning source code: https://github.com/zccodere/s…

Chapter 1: Learning Guide

1-1 Learning Guide

Application requirements

Moocnet_ Learning summary of

Learning objectives

1. Application scenarios of file reading and writing
2. Understand the file storage mechanism of IOS
3. Use basic file reading and writing for development

Chapter 2: introduction to sandbox

2-1 sandbox introduction

Schematic diagram of sandbox mechanism

Moocnet_ Learning summary of

Applications can only access files in their own application directory.
sand box

1. Documents: file data generated by program creation or application browsing
2. Library: the default setting or status information of the program is saved in this directory
3. TMP: provides a place to create temporary files instantly, but does not require persistence

Schematic diagram of file directory

Moocnet_ Learning summary of

Path processing

1. Processing of sandbox path
2. Processing of nsstring classpath function
3. About nsdata

2-2 get documents path

Code demonstration:

//Get the path to the sandbox
- (NSString *)getHomePath{
    NSString *homePath = NSHomeDirectory();
    NSLog(@"HomePath = %@",homePath);
    return homePath;
}

//Get documents path
- (NSString *)getDocumentsPath{
    //Retrieve the specified path in the application
    //The first parameter: the path name of the search
    //Second parameter: restricted in sandbox
    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [docPaths lastObject];
    NSLog(@"DocumentPath = %@",documentPath);
    return documentPath;
}

2-3 get library and TMP path

Code demonstration:

//Get library path
- (NSString *)getLibraryPath{
    NSArray *libPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryPath = [libPaths firstObject];
    NSLog(@"LibraryPath = %@",libraryPath);
    return libraryPath;
}

//Get TMP path
- (NSString *)getTmpPath{
    NSString *tmpPath = NSTemporaryDirectory();
    NSLog(@"TmpPath = %@",tmpPath);
    return tmpPath;
}

Chapter 3: data conversion

3-1 processing of path function of nsstring class

Code demonstration:

//Processing of path function of nsstring class
- (void)parsePath {
    NSString *path = @"/data/Containers/Data/Application/test.png";
    //Get 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);
    //Remove the last component of the path
    NSString *string = [path stringByDeletingLastPathComponent];
    NSLog(@"LastPath = %@",string);
    //Additional name.txt
    NSString *addString = [string stringByAppendingPathComponent:@"name.txt"];
    NSLog(@"AddString = %@",addString);
}

3-2 nsdata data conversion

Code demonstration:

//Nsdata 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 4: Operation Document

4-1 create folder using nsfilemanager

File operation function

1. Nsfilehandle class is mainly used to read and write file contents
2. Nsfilemanager class is mainly used to operate files (delete, create, etc.)

Code demonstration:

//Create folder
- (void)createFolder {
    NSString *docPath = [self getDocumentsPath];
    Nsstring * testpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    //Withintermediatedirectories yes can be overridden and no cannot be overridden
    BOOL result = [manager createDirectoryAtPath:testPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (result) {
        Nslog (@ "folder created successfully");
    } else{
        Nslog (@ "folder creation failed");
    }
}

//Creating files
- (void)createFile {
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    
    Nsstring * filepath = [dirpath stringbyappendingpathcomponent: @ "my notes. TXT"];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    BOOL result = [manager createFileAtPath:filePath contents:nil attributes:nil];
    if (result) {
        Nslog (@ "file created successfully");
    } else{
        Nslog (@ "file creation failed");
    }
}

4-2 write file

Code demonstration:

//Write to file
- (void)writeFile {
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    Nsstring * filepath = [dirpath stringbyappendingpathcomponent: @ "my notes. TXT"];
    
    Nsstring * content = @ "test notes";
    
    BOOL result = [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (result) {
        Nslog (@ "file written successfully");
    } else{
        Nslog (@ "file write failed");
    }
    
}

4-3 additional document content

Code demonstration:

//Additional document content
- (void) addFileContent{
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    Nsstring * filepath = [dirpath stringbyappendingpathcomponent: @ "my notes. TXT"];
    
    //Open the file to be updated
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    //Jumps 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 the file
    [fileHandle closeFile];
}

4-4 deleting 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 file
- (void)removeFile{
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    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 (@ "file deleted successfully");
        }else{
            Nslog (@ "file deletion failed");
        }
    }else{
        The nslog (@ "file does not exist. File path =% @ ", filepath);
        return;
    }
}

Chapter 5: Examples

5-1 instance operation

Example description

1. Get the pictures and save them to the local designated folder
2. Read the pictures in the local designated folder for display [after class practice]

Code demonstration:

//Write picture
- (void)writeImage{
    UIImage *testImage = [UIImage imageNamed:@"1.jpg"];
    NSData *imageData = UIImagePNGRepresentation(testImage);
    
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    Nsstring * filepath = [dirpath stringbyappendingpathcomponent: @ "picture"];
    
    [imageData writeToFile:filePath atomically:YES];
}

Chapter 6: course summary

6-1 course summary

Course review

Application scenarios
sand box 
Path processing
File processing example

Complete code of 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];
}

//Get the path to the sandbox
- (NSString *)getHomePath{
    NSString *homePath = NSHomeDirectory();
    NSLog(@"HomePath = %@",homePath);
    return homePath;
}

//Get documents path
- (NSString *)getDocumentsPath{
    //Retrieve the specified path in the application
    //The first parameter: the path name of the search
    //Second parameter: restricted in sandbox
    NSArray *docPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [docPaths lastObject];
    NSLog(@"DocumentPath = %@",documentPath);
    return documentPath;
}

//Get library path
- (NSString *)getLibraryPath{
    NSArray *libPaths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryPath = [libPaths firstObject];
    NSLog(@"LibraryPath = %@",libraryPath);
    return libraryPath;
}

//Get 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";
    //Get 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);
    //Remove the last component of the path
    NSString *string = [path stringByDeletingLastPathComponent];
    NSLog(@"LastPath = %@",string);
    //Additional name.txt
    NSString *addString = [string stringByAppendingPathComponent:@"name.txt"];
    NSLog(@"AddString = %@",addString);
}

//Nsdata 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: @ "moocnet"];
    
    NSFileManager *manager = [NSFileManager defaultManager];
    //Withintermediatedirectories yes can be overridden and no cannot be overridden
    BOOL result = [manager createDirectoryAtPath:testPath withIntermediateDirectories:YES attributes:nil error:nil];
    if (result) {
        Nslog (@ "folder created successfully");
    } else{
        Nslog (@ "folder creation failed");
    }
}

//Creating files
- (void)createFile {
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    
    Nsstring * filepath = [dirpath stringbyappendingpathcomponent: @ "my notes. TXT"];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    BOOL result = [manager createFileAtPath:filePath contents:nil attributes:nil];
    if (result) {
        Nslog (@ "file created successfully");
    } else{
        Nslog (@ "file creation failed");
    }
}

//Write to file
- (void)writeFile {
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    Nsstring * filepath = [dirpath stringbyappendingpathcomponent: @ "my notes. TXT"];
    
    Nsstring * content = @ "test notes";
    
    BOOL result = [content writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (result) {
        Nslog (@ "file written successfully");
    } else{
        Nslog (@ "file write failed");
    }
    
}

//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: @ "moocnet"];
    Nsstring * filepath = [dirpath stringbyappendingpathcomponent: @ "my notes. TXT"];
    
    //Open the file to be updated
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    //Jumps 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 the file
    [fileHandle closeFile];
}

//Delete file
- (void)removeFile{
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    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 (@ "file deleted successfully");
        }else{
            Nslog (@ "file deletion failed");
        }
    }else{
        The nslog (@ "file does not exist. File path =% @ ", filepath);
        return;
    }
}

//Write picture
- (void)writeImage{
    UIImage *testImage = [UIImage imageNamed:@"1.jpg"];
    NSData *imageData = UIImagePNGRepresentation(testImage);
    
    NSString *docPath = [self getDocumentsPath];
    Nsstring * dirpath = [docpath stringbyappendingpathcomponent: @ "moocnet"];
    Nsstring * filepath = [dirpath stringbyappendingpathcomponent: @ "picture"];
    
    [imageData writeToFile:filePath atomically:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

Recommended Today

Hot! Front and rear learning routes of GitHub target 144K

Hello, Sifu’s little friend. I’m silent Wang Er. Last week, while appreciating teacher Ruan Yifeng’s science and technology weekly, I found a powerful learning route, which has been marked with 144K on GitHub. It’s very popular. It covers not only the front-end and back-end learning routes, but also the operation and maintenance learning routes. As […]