---
title: "保存并获取数据"
author: "xiaotongeye"
date: "2014-09-27T19:38:38Z"
tags: []
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2014-09-27T17:18:38Z"
id: 2122995
url: "https://xiaotongeye.iteye.com/blog/2122995"
---

在IOS开发过程中，经常会遇到数据保存的问题，现在主要说一下用write方法保存数据，并在需要使用时获取数据，使用write to file方法可以使数据永久的保存在磁盘中，具体方法：
```第一步：获得文件即将保存的路径：

NSArray*paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);  
    NSString *path=[paths objectatindex:0];
    NSLog(@"path = %@",path);

```


```第二步：生成在该路径下的文件：

NSString *FileName=[documentdirectory stringbyappendingpathcomponent:@"test.plist"];//test.plist就是保存文件的文件名

```


```第三步：定义一个字典，并将字典添加到文件中

NSDictionary *dic = [nsdictionarydictionarywithobjectsandkeys:label2.text,@"1",label4.text,@"2",label6.text,@"3", label7.text,@"4", nil];//其中label.text是想保存的value值，并在后边获取
    [dic writetofile:filename atomically:yes];

```


```第四步：获取数据

NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
    NSString *path=[paths objectatindex:0];//获取数据所在的路径
    NSLog(@" %@",path);
    NSString *file=[path stringbyappendingpathcomponent:@"test.plist"];//获取数据的文件
    dic2 = [nsdictionary dictionarywithcontentsoffile:file];//将获取的数据定义到另一个字典中
    NSLog(@" %@",dic2);

```

这是在不同的controller之间获取数据，若是在同一个controller获取数据则不需要获取路径直接用self.path就行。