簡(jiǎn)單數(shù)據(jù)的讀寫(xiě)操作
iOS中提供了對(duì)一下四種(包括他們的子類(lèi))可直接進(jìn)行文件存取的操作
- NSString(字符串)
- NSArray(數(shù)組)
- NSdictionary(字典)
- NSData(數(shù)據(jù))
獲取Document文件目錄下的文件路徑
- (NSString *)GetThefilePath:(NSString *)filePath{
NSString *Path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES)firstObject]stringByAppendingPathComponent:filePath];
return Path;
}
字符串的存取
存儲(chǔ)一個(gè)字符串
- 獲取要存儲(chǔ)的文件路徑
NSString *filePath = [self GetThefilePath:@"name.plist"];
- 將一個(gè)字符串寫(xiě)入到一個(gè)文件中
NSString *name = @"藍(lán)歐科技";
[name writeToFile: filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
- 將一個(gè)字符串歸檔到一個(gè)文件中
NSString *name = @"藍(lán)歐科技";
[NSKeyedArchiver archiveRootObject:name toFile:[self GetThefilePath:@"name1.plist"]];
取出一個(gè)字符串
- 簡(jiǎn)單的讀取
NSString *string = [NSString stringWithContentsOfFile:
[self GetThefilePath:@"name.plist"] encoding:NSUTF8StringEncoding error:NULL];
- 反歸檔一個(gè)字符串
NSString *string = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"name1.plist"]];
數(shù)組的存取
存儲(chǔ)一個(gè)數(shù)組
- 將一個(gè)數(shù)組寫(xiě)入到文件中
//創(chuàng)建一個(gè)數(shù)組
NSArray *array = @[@"小李",@"小紅",@"Mark"];
[array writeToFile:[self GetThefilePath:@"array.txt"] atomically:YES];
- 將一個(gè)數(shù)組歸檔到一個(gè)文件中
NSArray *array = @[@"小李",@"小紅",@"Mark"];
[NSKeyedArchiver archiveRootObject:array toFile:[self GetThefilePath:@"array.txt"]];
讀取一個(gè)數(shù)組
- 簡(jiǎn)單的讀取
NSArray *array_1 = [NSArray arrayWithContentsOfFile:[self GetThefilePath:@"array.txt"]];
- 反歸檔一個(gè)數(shù)組
NSArray *array_2 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"array.txt"]];
字典的存取
字典的存儲(chǔ)
- 簡(jiǎn)單的寫(xiě)入
//創(chuàng)建一個(gè)字典
NSDictionary *dictionary = @{@"name":@"小紅",@"age":@22,@"sex":@"男"};
[dictionary writeToFile:[self GetThefilePath:@"dictionary.txt"] atomically:YES];
- 將字典歸檔到文件中
//創(chuàng)建一個(gè)字典
NSDictionary *dictionary = @{@"name":@"小紅",@"age":@22,@"sex":@"男"};
[NSKeyedArchiver archiveRootObject:dictionary toFile:[self GetThefilePath:@"dictionary.txt"]];
字典的讀取
- 簡(jiǎn)單的讀取
NSDictionary *dictionary_1 = [NSDictionary dictionaryWithContentsOfFile:
[self GetThefilePath:@"dictionary.txt"]];
- 返歸檔一個(gè)字典
NSDictionary *dictionary_2 = [NSKeyedUnarchiver unarchiveObjectWithFile:
[self GetThefilePath:@"dictionary.txt"]];
NSData的存取
NSData的存儲(chǔ)
- 先將一個(gè)圖片轉(zhuǎn)換為NSData格式骑篙,然后在進(jìn)行存儲(chǔ)
NSData *imageData = UIImagePNGRepresentation([UIImage imageNamed:@"4.png"]);
- 將NSData數(shù)據(jù)寫(xiě)入到文件中
[imageData writeToFile:[self GetThefilePath:@"image.txt"] atomically:YES];
- 將NSData數(shù)據(jù)進(jìn)行歸檔
[NSKeyedArchiver archiveRootObject:imageData toFile:[self GetThefilePath:@"image.txt"]];
NSData的讀取
- 從文件讀取出來(lái)的還是一個(gè)NSData類(lèi)型的數(shù)據(jù)
NSData *imageData_1 = [NSData dataWithContentsOfFile:[self GetThefilePath:@"image.txt"]];
- 反歸檔一個(gè)NSData
NSData *imageData_1 = [NSKeyedUnarchiver unarchiveObjectWithFile:[self GetThefilePath:@"image.txt"]];