IOS study notes (seventeen) -- file operations (NSFileManager)

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

Sandbox mechanism of iOS, applications can only access to their application file directory. Unlike iOS Android, no SD card concept, cannot directly access the image, video and other content. The application of iOS generated content, such as images, documents, cache contents must be stored in their sandbox. By default, each box contains 3 folders: Documents, Library and tmp. Library contains Caches, Preferences directory.

The complete path above: user -> resource library>Application Support->iPhone Simulator->6.1->Aplications


Documents: Apple recommends the program creates the file and browse the file data generated are stored in the directory, iTunes backup and recovery time will be included in this directory

Library: Procedures for the storage of the default settings or other status information,

Library/Caches: For the cache files, persistent data storage applications, for the upgrade of application or application after the closure of the data, not be the iTunes synchronization, so in order to reduce synchronization time, can consider to be some big file without the need to back up your files in this directory.

tmp: Provide an instant create temporary file in place, but does not need to be persistent, in the application is closed, the directory data will be deleted, the system may also be removed when the program is not running.

APP  Sandbox

IOS how to obtain the sandbox path, how to operate the file? The following answer.

 

Gets the application sandbox root path:


-(void)dirHome{
    NSString *dirHome=NSHomeDirectory();    
    NSLog(@"app_home: %@",dirHome);
}

Access to Documents directory path:



//Access to Documents directory
-(NSString *)dirDoc{
    //[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
	NSString *documentsDirectory = [paths objectAtIndex:0];
    NSLog(@"app_home_doc: %@",documentsDirectory);
    return documentsDirectory;
}

Access to Library directory path:



//Access to Library directory
-(void)dirLib{
    //[NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
    NSString *libraryDirectory = [paths objectAtIndex:0];
    NSLog(@"app_home_lib: %@",libraryDirectory);
}

Access to Cache directory path:



//Access to Cache directory
-(void)dirCache{
    NSArray *cacPath = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
    NSString *cachePath = [cacPath objectAtIndex:0];
    NSLog(@"app_home_lib_cache: %@",cachePath);
}

Access to Tmp directory path:




//Access to Tmp directory
-(void)dirTmp{
    //[NSHomeDirectory() stringByAppendingPathComponent:@"tmp"];
    NSString *tmpDirectory = NSTemporaryDirectory();
    NSLog(@"app_home_tmp: %@",tmpDirectory);
}


Create folder:


//Create folder
-(void *)createDir{
    NSString *documentsPath =[self dirDoc];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    // Create a directory
    BOOL res=[fileManager createDirectoryAtPath:testDirectory withIntermediateDirectories:YES attributes:nil error:nil];
    if (res) {
        NSLog(@"The folder was created successfully");
    }else
        NSLog(@"Folder creation failed");
 }

Create a file


//Create a file
-(void *)createFile{
    NSString *documentsPath =[self dirDoc];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    BOOL res=[fileManager createFileAtPath:testPath contents:nil attributes:nil];
    if (res) {
        NSLog(@"The file was created successfully: %@" ,testPath);
    }else
        NSLog(@"File creation failed");
}

To write data to a file:



//The write file
-(void)writeFile{
    NSString *documentsPath =[self dirDoc];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    NSString *content=@"Test writing content´╝ü";
    BOOL res=[content writeToFile:testPath atomically:YES encoding:NSUTF8StringEncoding error:nil];
    if (res) {
        NSLog(@"File write success");
    }else
        NSLog(@"File write failure");
}

Read data:



//Read file
-(void)readFile{
    NSString *documentsPath =[self dirDoc];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
//    NSData *data = [NSData dataWithContentsOfFile:testPath];
//    NSLog(@"File read: %@",[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]);
    NSString *content=[NSString stringWithContentsOfFile:testPath encoding:NSUTF8StringEncoding error:nil];
    NSLog(@"File read: %@",content);
}

File attribute:



//File attribute
-(void)fileAttriutes{
    NSString *documentsPath =[self dirDoc];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];
    NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:testPath error:nil];   
    NSArray *keys;
    id key, value;
    keys = [fileAttributes allKeys];
    int count = [keys count];
    for (int i = 0; i <count; i++)
    {
        key = [keys objectAtIndex: i];
        value = [fileAttributes objectForKey: key];
        NSLog (@"Key: %@ for value: %@", key, value);
    }
}


Delete files:

  

//Delete files
-(void)deleteFile{
    NSString *documentsPath =[self dirDoc];
    NSString *testDirectory = [documentsPath stringByAppendingPathComponent:@"test"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *testPath = [testDirectory stringByAppendingPathComponent:@"test.txt"];   
    BOOL res=[fileManager removeItemAtPath:testPath error:nil];
    if (res) {
        NSLog(@"File deleted successfully");
    }else
        NSLog(@"Failed to delete the file");   
    NSLog(@"If the file exists: %@",[fileManager isExecutableFileAtPath:testPath]?@"YES":@"NO");
}





/**

* @Author Zhang Xingye

*  

*  Introduction to iOS group: 83702688

*  Android development of advanced group: 241395671

*  My Sina micro-blog: @ Zhang Xingye TBOW

*  My mailbox: xy-zhang#163.com(#->@)

*/

 

https://developer.apple.com/library/ios/#documentation/FileManagement/Conceptual/FileSystemProgrammingGUide/FileSystemOverview/FileSystemOverview.html#//apple_ref/doc/uid/TP40010672-CH2-SW2



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Daniel at November 16, 2013 - 3:24 PM