一.在Documents、tmp和Library中隱藏檔
Documents:用於儲存應用程式中經常需要讀取或寫入的常規檔案。
tmp:用於儲存應用程式運行時產生的檔案。(隨著應用程式的關閉失去了利用價值)
Library:一般存放應用程式的設定檔,比如說plist類型的檔案。
二.讀取和寫入檔案
1.建立Empty Application應用程式,添加HomeViewController檔案
HomeViewController.h代碼:
#import <UIKit/UIKit.h>
@interface HomeViewController : UIViewController{ }- (NSString *) documentsPath;//負責擷取Documents檔案夾的位置- (NSString *) readFromFile:(NSString *)filepath; //讀取檔案內容- (void) writeToFile:(NSString *)text withFileName:(NSString *)filePath;//將內容寫到指定的檔案@end
HomeViewController.m代碼:
#import "HomeViewController.h"@interface HomeViewController ()@end@implementation HomeViewController//負責擷取Documents檔案夾的位置- (NSString *) documentsPath{ NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsdir = [paths objectAtIndex:0]; return documentsdir;}
//讀取檔案內容 - (NSString *) readFromFile:(NSString *)filepath{ if ([[NSFileManager defaultManager] fileExistsAtPath:filepath]){ NSArray *content = [[NSArray alloc] initWithContentsOfFile:filepath]; NSString *data = [[NSString alloc] initWithFormat:@"%@", [content objectAtIndex:0]]; [content release]; return data; } else { return nil; }}//將內容寫到指定的檔案 - (void) writeToFile:(NSString *)text withFileName:(NSString *)filePath{ NSMutableArray *array = [[NSMutableArray alloc] init]; [array addObject:text]; [array writeToFile:filePath atomically:YES]; [array release];}
-(NSString *)tempPath{ return NSTemporaryDirectory();}- (void)viewDidLoad{ NSString *fileName = [[self documentsPath] stringByAppendingPathComponent:@"content.txt"]; //NSString *fileName = [[self tempPath] stringByAppendingPathComponent:@"content.txt"]; [self writeToFile:@"蘋果的魅力!" withFileName:fileName]; NSString *fileContent = [self readFromFile:fileName]; NSLog(fileContent); [super viewDidLoad];}@end
: