iOS數(shù)據(jù)存儲

簡單數(shù)據(jù)的存儲

1. 獲取沙盒的位置

NSString *libraryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];

也可以使用

NSString *homePath = NSHomeDirectory();
    NSString *documentPath2 = [homePath stringByAppendingPathComponent:@"Documents"];

2. 簡單數(shù)據(jù)的存儲

2.1 NSString
(1)創(chuàng)建txt文件

NSString *str = @"ADC";
    NSString *strFilePath = [documentPath stringByAppendingPathComponent:@"str.txt"];

(2)寫入數(shù)據(jù)

[str writeToFile:strFilePath atomically:YES];

(3)讀取數(shù)據(jù)

NSString *readStr = [[NSString alloc] initWithContentsOfFile:strFilePath encoding:NSUTF8StringEncoding error:nil];

2.2 NSArray

//先創(chuàng)建一個存儲array對象的txt文件路徑
NSString *arrPath = [documentPath stringByAppendingPathComponent:@"array.txt"];
//使用字面量創(chuàng)建Array
    NSArray *nameArr = @[];
//將數(shù)據(jù)寫入txt文件路徑
    [nameArr writeToFile:arrPath atomically:YES];
//從路徑讀取出數(shù)據(jù)
    NSArray *arr = [NSArray arrayWithContentsOfFile:arrPath];

2.3 字典

//字典的處理步驟同NSArray  
NSString *dictPath = [documentPath stringByAppendingPathComponent:@"dict.txt"];
    
    NSDictionary *dict = @{};
    [dict writeToFile:dictPath atomically:YES];
    
    NSDictionary *readDict = [NSDictionary dictionaryWithContentsOfFile:dictPath];

2.4 NSData

NSString *imgPath = [documentPath stringByAppendingPathComponent:@"img.txt"];
    UIImage *image = [UIImage imageNamed:@"address"];
//將圖片轉(zhuǎn)換成NSData類型
    NSData *imgData = UIImagePNGRepresentation(image);
    
    [imgData writeToFile:imgPath atomically:YES];
    //讀取圖片
    UIImage *img = [UIImage imageWithContentsOfFile:imgPath];

2.5 從資源包讀取圖片

//獲取絕對路徑
NSString *imagePath = [[NSBundle mainBundle] pathForResource:@"address" ofType:@"png"];
//通過路徑加載圖片
    UIImage *image1 = [UIImage imageWithContentsOfFile:imagePath];
    
    imageView.image = image1;
    
    [self.view addSubview:imageView];
    
    UIView *view = [[NSBundle mainBundle] loadNibNamed:@"a" owner:self options:nil][0];

數(shù)據(jù),文件操作

  1. 聲明文件的路徑
NSString *documentPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
  1. 創(chuàng)建txt文件及其路徑
NSString *filePath = [documentPath stringByAppendingPathComponent:@"file.txt"];
  1. 創(chuàng)建FileManager,并初始化文件
NSFileManager *fileManager = [NSFileManager defaultManager];
    
    [fileManager createFileAtPath:filePath contents:strData attributes:nil];
  1. 讀取數(shù)據(jù)
NSData *readStrData = [fileManager contentsAtPath:filePath];
    NSString *str1 = [[NSString alloc] initWithData:readStrData encoding:NSUTF8StringEncoding];
  1. 移動文件
    5.1 創(chuàng)建目標文件的路徑
NSString *moveFilePath = [topath stringByAppendingPathComponent:@"file.txt"];

5.2 移動文件

    [fileManager moveItemAtPath:filePath toPath:moveFilePath error:nil];
  1. 復(fù)制文件
NSString *copyPath = [documentPath stringByAppendingPathComponent:@"備份/copy.txt"];
    
    [fileManager createDirectoryAtPath:[copyPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil];
    
    [fileManager copyItemAtPath:moveFilePath toPath:copyPath error:nil];
  1. 獲取文件信息(文件大小)
NSDictionary *dic = [fileManager attributesOfItemAtPath:filePath error:nil];
    
    NSInteger fileLength = [dic[NSFileSize] integerValue];
  1. 判斷文件是否存在
[fileManager fileExistsAtPath:filePath]

使用NSFileHandle操作文件

//先通過fileManager創(chuàng)建文件并在里面寫入內(nèi)容
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    NSString *documentPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"file.txt"];
    
    [fileManager createFileAtPath:filePath contents:[@"abc" dataUsingEncoding:NSUTF8StringEncoding] attributes:nil];

修改內(nèi)容

NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:filePath];
    //查找到文件最末端
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[@"123" dataUsingEncoding:NSUTF8StringEncoding]];
    
    [fileHandle closeFile];

讀取文件

NSFileHandle *readFileHandle = [NSFileHandle fileHandleForReadingAtPath:filePath];
    //讀取長度
    NSUInteger length = [[readFileHandle availableData] length];
    //設(shè)置偏移位置
    [readFileHandle seekToFileOffset:length/2];
    //從偏移位置開始讀取到文件末尾
    NSData *readData = [readFileHandle readDataToEndOfFile];
    
    NSString *readStr = [[NSString alloc] initWithData:readData encoding:NSUTF8StringEncoding];

復(fù)制文件

NSString *copypath = [documentPath stringByAppendingPathComponent:@"copy.txt"];
    [fileManager createFileAtPath:copypath contents:nil attributes:nil];

    //打開文件準備寫入
    NSFileHandle *copyHandle = [NSFileHandle fileHandleForWritingAtPath:copypath];
    //writeData會直接覆蓋原來的
    [copyHandle writeData:readData];
    
    [copyHandle closeFile];

文件的歸檔與反歸檔

要進行歸檔, 必須先讓類繼承<NSCoding>并實現(xiàn)兩個方法

//反序列化
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    self = [super init];
    if (self) {
        self.name = [aDecoder decodeObjectForKey:@"name"];
        self.age = [aDecoder decodeIntegerForKey:@"age"];
    }
    return self;
}
//序列化
- (void)encodeWithCoder:(NSCoder *)aCoder {
    [aCoder encodeObject:self.name forKey:@"name"];
    [aCoder encodeInteger:self.age forKey:@"age"];
}

歸檔過程:Person對象-->NSData-->writeFile

NSMutableData *mulData = [NSMutableData data];
    NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:mulData];
    [archiver encodeObject:person forKey:@"Person"];
    [archiver finishEncoding];

寫入文件

NSString *personDataPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/person.txt"];
   
    [mulData writeToFile:personDataPath atomically:YES];

反歸檔過程: 從文件里面讀取-->NSData-->Person對象

NSData *personData = [NSData dataWithContentsOfFile:personDataPath];
    NSKeyedUnarchiver *unarchiver = [[NSKeyedUnarchiver alloc] initForReadingWithData:personData];
    Person *person1 = [unarchiver decodeObjectForKey:@"Person"];
    NSLog(@"perosn1 = %@", person1);

另外,還有一個系統(tǒng)單利類可以進行數(shù)據(jù)存儲

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:@"123" forKey:@"userName"];
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末捡需,一起剝皮案震驚了整個濱河市户秤,隨后出現(xiàn)的幾起案子鹅颊,更是在濱河造成了極大的恐慌,老刑警劉巖近零,帶你破解...
    沈念sama閱讀 216,591評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異它碎,居然都是意外死亡,警方通過查閱死者的電腦和手機卿操,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,448評論 3 392
  • 文/潘曉璐 我一進店門警检,熙熙樓的掌柜王于貴愁眉苦臉地迎上來孙援,“玉大人,你說我怎么就攤上這事扇雕⊥厥郏” “怎么了?”我有些...
    開封第一講書人閱讀 162,823評論 0 353
  • 文/不壞的土叔 我叫張陵镶奉,是天一觀的道長础淤。 經(jīng)常有香客問我,道長哨苛,這世上最難降的妖魔是什么值骇? 我笑而不...
    開封第一講書人閱讀 58,204評論 1 292
  • 正文 為了忘掉前任,我火速辦了婚禮移国,結(jié)果婚禮上吱瘩,老公的妹妹穿的比我還像新娘。我一直安慰自己迹缀,他們只是感情好使碾,可當我...
    茶點故事閱讀 67,228評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著祝懂,像睡著了一般票摇。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上砚蓬,一...
    開封第一講書人閱讀 51,190評論 1 299
  • 那天矢门,我揣著相機與錄音,去河邊找鬼灰蛙。 笑死祟剔,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的摩梧。 我是一名探鬼主播物延,決...
    沈念sama閱讀 40,078評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼仅父!你這毒婦竟也來了叛薯?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,923評論 0 274
  • 序言:老撾萬榮一對情侶失蹤笙纤,失蹤者是張志新(化名)和其女友劉穎耗溜,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體省容,經(jīng)...
    沈念sama閱讀 45,334評論 1 310
  • 正文 獨居荒郊野嶺守林人離奇死亡抖拴,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,550評論 2 333
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了蓉冈。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片城舞。...
    茶點故事閱讀 39,727評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡轩触,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出家夺,到底是詐尸還是另有隱情脱柱,我是刑警寧澤,帶...
    沈念sama閱讀 35,428評論 5 343
  • 正文 年R本政府宣布拉馋,位于F島的核電站榨为,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏煌茴。R本人自食惡果不足惜随闺,卻給世界環(huán)境...
    茶點故事閱讀 41,022評論 3 326
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望蔓腐。 院中可真熱鬧矩乐,春花似錦、人聲如沸回论。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,672評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽傀蓉。三九已至欧漱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間葬燎,已是汗流浹背误甚。 一陣腳步聲響...
    開封第一講書人閱讀 32,826評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留谱净,地道東北人窑邦。 一個月前我還...
    沈念sama閱讀 47,734評論 2 368
  • 正文 我出身青樓,卻偏偏與公主長得像岳遥,于是被迫代替她去往敵國和親奕翔。 傳聞我的和親對象是個殘疾皇子裕寨,可洞房花燭夜當晚...
    茶點故事閱讀 44,619評論 2 354

推薦閱讀更多精彩內(nèi)容

  • 學(xué)習了數(shù)據(jù)存儲的NSUserDefaults浩蓉,歸檔和解檔,對于項目開發(fā)中如果要存儲一些文件宾袜,比如圖片捻艳,音頻,...
    今天又要上班嗎閱讀 866評論 0 1
  • 27庆猫、ViewController的didReceiveMemoryWarning是在什么時候調(diào)用的认轨?默認的操作是...
    煙雨平生花飛舞閱讀 575評論 0 1
  • 一、iOS中的沙盒機制 iOS應(yīng)用程序只能對自己創(chuàng)建的文件系統(tǒng)讀取文件月培,這個獨立嘁字、封閉恩急、安全的空間,叫做沙盒纪蜒。它一...
    1d5cb7cff98d閱讀 1,770評論 0 0
  • iOS開發(fā)-文件管理(一) 一衷恭、iOS中的沙盒機制 iOS應(yīng)用程序只能對自己創(chuàng)建的文件系統(tǒng)讀取文件,這個獨立纯续、封閉...
    MacShare閱讀 1,800評論 0 6
  • 還記得在《高效能人士的七個習慣》培訓(xùn)課上使命宣言那個環(huán)節(jié)Gus的開場猬错,娓娓道來講述著他的過往窗看。 原來他的父母輩一樣...
    Rafen閱讀 1,052評論 9 8