Ios file and folder Management

Source: Internet
Author: User
Tags tmp folder


Obtain the path to the most common folders on the disk.

We know that apps on apple are running in their sandbox, and few do not have sufficient permissions to deal with file resources outside the sandbox. Generally, the file directory of an application is as follows:


The most common operations to obtain the folder path under the application directory:

What is the URLsFZ limit of the NSFileManager class? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> encrypt/decrypt + cjxwp1_vcd4kphagy2xhc3m9" p1 "> URLsForDirectory:

This parameter is the dictionary object to be searched. For this parameter, an NSSearchPath directory dictionary is passed. I will discuss this parameter in detail later.

InDomains:

This parameter specifies where you search for the specified directory. This parameter must be an NSSearchDomainMask enumeration value.

If you want to obtain the path of the Document folder of your application, you will find it so simple:

 NSFileManager *fileManager = [[NSFileManager alloc] init];    NSArray *urls = [fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];    if ([urls count] > 0) {        NSURL *documentsFolder = urls[0];        NSLog(@"%@",documentsFolder);    }else{        NSLog(@"Could not find the Documents folder");    }

Below are all the important parameter values that you can pass in the NSFileManager class method URLsForDirectory: inDomains:

URLsForDirectory

NSLibraryDirectory: Mark the library folder of the application.

NSCachesDirectory indicates the caches folder, which has been explained previously.

NSDocumentDirectory: Mark the document folder.

InDomains

NSUserDomainMask marks the search for the folder path in the current user folder. In OS X, this folder is ~ /.

If you want to obtain the path of the tmp folder, use the C function NSTemporaryDirectory () like this ();

NSString *tempDirectory = NSTemporaryDirectory();        NSLog(@"Temp Directory = %@",tempDirectory);

Perform read/write operations on files
// Write-(BOOL) writeText :( NSString *) paramText toPath :( NSString *) paramPath {return [paramText writeToFile: paramPath atomically: YES encoding: NSUTF8StringEncoding error: nil];}

// Read-(NSString *) readTextFromPath :( NSString *) paramPath {return [[NSString alloc] initWithContentsOfFile: paramPath encoding: NSUTF8StringEncoding error: nil];}

- (void)viewDidLoad{    [super viewDidLoad];    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"MyFile.txt"];    if ([self writeText:@"Hello,World!" toPath:filePath]) {        NSString *readText = [self readTextFromPath:filePath];        if ([readText length]) {            NSLog(@"Text read from disk = %@",readText);        }else{            NSLog(@"Failed to read the text from disk");        }    }else{        NSLog(@"Failed to write the file");    }}


In the form of an array to the file:
    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"MyFile.txt"];    NSArray *arrayOfNames = @[@"Steve",@"John",@"Aaron"];    if ([arrayOfNames writeToFile:filePath atomically:YES]) {        NSArray *readArray = [[NSArray alloc] initWithContentsOfFile:filePath];        if ([readArray count]) {            NSLog(@"Read the array back from disk just fine");        }else{            NSLog(@"Failed to read the array back from disk");        }    }else{        NSLog(@"Failed to save the array to disk");    }

The NSArray instance method writeToFile: atomiclly can only save arrays containing the following object types:

NSString

NSDictionary

NSArray

NSData

NSNumber

NSDate

If you try to insert other objects into the array, the data cannot be saved to the disk.


The dictionary has the same method as the array for writing data to the disk and reading data back to the dictionary object. The method name is also identical, and the storage rules of the array are also applicable to the dictionary.

    NSString *filePath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"MyFile.txt"];    NSDictionary *dict = @{@"firstName": @"Aaron",                           @"lastName":@"zheng",                           @"age":@"21"};    if ([dict writeToFile:filePath atomically:YES]) {        NSDictionary *readDictionary = [[NSDictionary alloc] initWithContentsOfFile:filePath];        if ([readDictionary isEqualToDictionary:dict]) {            NSLog(@"The file we read is the same one as the one we saved");        }else{            NSLog(@"Failed to read the dictionary from disk");        }    }else{        NSLog(@"Failed to write the dictionay to disk");    }


Create a folder in the disk:

// Create a folder on the disk-(void) createDirectory {NSFileManager * fileManager = [[NSFileManager alloc] init]; NSString * tempDir = NSTemporaryDirectory (); NSString * path = [tempDir stringByAppendingPathComponent: @ "images"]; NSError * error; if ([fileManager createDirectoryAtPath: path withIntermediateDirectories: YES attributes: nil error: & error]) {NSLog (@ "Successfully created the directory");} else {NSLog (@ "Failed to create the directory, ERROR = % @", error );}}

The above withIntermediateDirectories: YES parameter is set to YES. when creating the deepest folder, if the parent folder does not exist, the system will create it for you directly.
Delete files and folders

// Delete files and folders-(void) removeDir {NSFileManager * fileManager = [[NSFileManager alloc] init]; NSString * tempDir = NSTemporaryDirectory (); NSString * path = [tempDir stringByAppendingString: @ "images"]; NSError * error; if ([fileManager removeItemAtPath: path error: & error] = NO) {NSLog (@ "Failed to remove path % @, ERROR = % @ ", path, error );}}

Well, let's write it here first. I don't want to write it anymore. I have time to write about the secure processing of files on the disk. Note: The examples in this article are all taken from the book "ios 6 Programming Cookbook, translation is organized by DevDiv netizens to support technology and information sharing!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.