天天看點

IOS檔案沙盒在進行IPhone開發的時候,常常需要将簡單的資料儲存到檔案中,以便下次再重新打開的時候能夠讀取檔案中儲存的資料。如何尋找沙盒檔案?如何建立自定義檔案名檔案?當開發一個應用要适應使用者還沒點選儲存,但一個電話打過來,要先接電話,是以就要讓系統自動先儲存目前的資料,适合實作?

下面就來做一個簡單的demo:

右擊文本框,發現他的Did End On Exit事件,然後拖放到.h檔案中,建立一個click事件

- (IBAction)click:(id)sender {

    [senderresignFirstResponder];

}

點選mac系統上最上面一行的前往功能,然後按住alt鍵會顯示出資源檔案,該檔案一般是隐藏的,前往->資源庫->Application Support->iPhone Simulator->6.1->Applications->

選擇自定義的檔案->Library或者Documents(存儲大資料,自定義檔案名的檔案都在這裡面)

//擷取沙盒檔案路徑

-(NSString *)getPath

{

    //用來獲得Document位址

    NSArray *arr = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//注意:這裡是NSDocument不是NSDocumentation,特别注意

    NSLog(@"%@",arr);

    //在位址上增加檔案

    NSString *path = [arr[0] stringByAppendingPathComponent:@"abc.plist"];

    NSLog(@"%@",path);

    return path;

//建立自定義檔案,并存儲或者擷取檔案中資料

- (void)viewDidLoad

    [super viewDidLoad];

    NSArray *arr = @[@"aaa",@"bbb",@"ccc"];

    [arr writeToFile:[self getPath] atomically:YES];

    //判斷是否有檔案

    if([[NSFileManager defaultManager] fileExistsAtPath:[self getPath]])

    {

        arr = [NSArray arrayWithContentsOfFile:[self getPath]];

        NSLog(@"%@",arr);

    }

    //擷取應用

    UIApplication *app = [UIApplication sharedApplication];

    //在通知中心添加一個觀察者,當符合UIApplicationWillResignActiveNotification條件時,調用方法

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(save:) name:UIApplicationWillResignActiveNotification object:app];

-(void)save:(id)sender

    NSArray *arr = @[self.text1.text1,self.text2.text];

本文轉蓬萊仙羽51CTO部落格,原文連結:http://blog.51cto.com/dingxiaowei/1366423,如需轉載請自行聯系原作者

繼續閱讀