iOS 簡單資料的讀寫

weixin_33936401發表於2016-05-07

簡單資料的讀寫操作

iOS中提供了對一下四種(包括他們的子類)可直接進行檔案存取的操作

  • NSString(字串)
  • NSArray(陣列)
  • NSdictionary(字典)
  • NSData(資料)

獲取Document檔案目錄下的檔案路徑

- (NSString *)GetThefilePath:(NSString *)filePath{
    NSString *Path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 
NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:filePath];
    return Path;
}

字串的存取

儲存一個字串

  • 獲取要儲存的檔案路徑
NSString *filePath = [self GetThefilePath:@"name.plist"];
  • 將一個字串寫入到一個檔案中
NSString *name = @"藍歐科技";
[name writeToFile: filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
  • 將一個字串歸檔到一個檔案中
NSString *name = @"藍歐科技";
[NSKeyedArchiver archiveRootObject:name toFile:[self GetThefilePath:@"name1.plist"]];

取出一個字串

  • 簡單的讀取
NSString *string = [NSString stringWithContentsOfFile:
[self GetThefilePath:@"name.plist"] encoding:NSUTF8StringEncoding error:NULL];
  • 反歸檔一個字串
NSString *string = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"name1.plist"]];

陣列的存取

儲存一個陣列

  • 將一個陣列寫入到檔案中
//建立一個陣列
NSArray *array = @[@"小李",@"小紅",@"Mark"];
[array writeToFile:[self GetThefilePath:@"array.txt"] atomically:YES];
  • 將一個陣列歸檔到一個檔案中
NSArray *array = @[@"小李",@"小紅",@"Mark"];
[NSKeyedArchiver archiveRootObject:array toFile:[self GetThefilePath:@"array.txt"]];

讀取一個陣列

  • 簡單的讀取
NSArray *array_1 = [NSArray arrayWithContentsOfFile:[self GetThefilePath:@"array.txt"]];
  • 反歸檔一個陣列
NSArray *array_2 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"array.txt"]];

字典的存取

字典的儲存

  • 簡單的寫入
//建立一個字典
NSDictionary *dictionary = @{@"name":@"小紅",@"age":@22,@"sex":@"男"};
[dictionary writeToFile:[self GetThefilePath:@"dictionary.txt"] atomically:YES];
  • 將字典歸檔到檔案中
//建立一個字典
NSDictionary *dictionary = @{@"name":@"小紅",@"age":@22,@"sex":@"男"};
[NSKeyedArchiver archiveRootObject:dictionary toFile:[self GetThefilePath:@"dictionary.txt"]];

字典的讀取

  • 簡單的讀取
NSDictionary *dictionary_1 = [NSDictionary dictionaryWithContentsOfFile:
[self GetThefilePath:@"dictionary.txt"]];
  • 返歸檔一個字典
NSDictionary *dictionary_2 = [NSKeyedUnarchiver unarchiveObjectWithFile:
[self GetThefilePath:@"dictionary.txt"]];

NSData的存取

NSData的儲存

  • 先將一個圖片轉換為NSData格式,然後在進行儲存
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"4.png"]);
  • 將NSData資料寫入到檔案中
[imageData writeToFile:[self GetThefilePath:@"image.txt"] atomically:YES];
  • 將NSData資料進行歸檔
[NSKeyedArchiver archiveRootObject:imageData toFile:[self GetThefilePath:@"image.txt"]];

NSData的讀取

  • 從檔案讀取出來的還是一個NSData型別的資料
NSData *imageData_1 = [NSData dataWithContentsOfFile:[self GetThefilePath:@"image.txt"]];
  • 反歸檔一個NSData
NSData *imageData_1 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"image.txt"]];

相關文章