保存一个 NSArray [英] Saving a NSArray

查看:26
本文介绍了保存一个 NSArray的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 NSArray 保存为文件或可能使用用户默认值.这就是我希望做的事情.

I would like to save an NSArray either as a file or possibly use user defaults. Here's what I am hoping to do.

  1. 检索已保存的 NSArray(如果有).
  2. 用它做点什么.
  3. 擦除保存的数据(如果有).
  4. 保存 NSArray.

这可能吗,如果可以,我应该怎么做?

Is this possible, and if so how should I do this?

推荐答案

NSArray 为你提供了两种方法来做你想做的事情:initWithContentsOfFile:writeToFile:atomically:

NSArray provides you with two methods to do exactly what you want: initWithContentsOfFile: and writeToFile:atomically:

一个简短的例子可能如下所示:

A short example might look like this:

//Creating a file path under iOS:
//1) Search for the app's documents directory (copy+paste from Documentation)
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//2) Create the full file path by appending the desired file name
NSString *yourArrayFileName = [documentsDirectory stringByAppendingPathComponent:@"example.dat"];

//Load the array
NSMutableArray *yourArray = [[NSMutableArray alloc] initWithContentsOfFile: yourArrayFileName];
if(yourArray == nil)
{
    //Array file didn't exist... create a new one
    yourArray = [[NSMutableArray alloc] initWithCapacity:10];

    //Fill with default values
}
...
//Use the content
...
//Save the array
[yourArray writeToFile:yourArrayFileName atomically:YES];

这篇关于保存一个 NSArray的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆