ios - 将 NSMutableArray 保存到文件

标签 ios objective-c

我想将一些 NSMutableArray 类型的数据存储到文件中。我尝试了以下代码,但它对我不起作用:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"test"];
[self.arrayHit writeToFile:filePath atomically:YES]

我不确定的是,stringByAppendingPathComponent 之后的路径,我只是在我的项目中创建一个空文件,结构如下所示: enter image description here 但过了一段时间,我在 StackOverflow 中看到一个答案提到上面的代码不能保留 NSMutableArray,而是适用于 NSArray,所以我尝试使用下面建议的代码来保留 NSMutableArray:

BOOL success = [NSKeyedArchiver archiveRootObject:self.arrayHit toFile:@"test"];

但仍然没有运气。

有两件事我不确定: 1.我应该创建什么文件来存储数据,因为我不知道,所以我只是创建了一个空文件(我看到还有其他选择,如属性列表、字符串文件、富文本文件等)见下图: enter image description here 2.我应该把数据放在什么路径下?如果文件和我的代码在同一个目录下,我可以直接使用@"test"吗?

最佳答案

解释你正在使用的代码发生了什么

你的第一段代码:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"test"];

[self.arrayHit writeToFile:filePath atomically:YES]

将文件写入您的用户 Documents 文件夹。因为这是 NSDocumentDirectoryNSUserDomainMask

在用户域中要求的

你的第二段代码:

 BOOL success = [NSKeyedArchiver archiveRootObject:self.arrayHit toFile:@"test_me"];

当从 Xcode 运行时将写入

~/Library/Developer/Xcode/DerivedData/myApp-cgammojtjqvbdcappvddborkhkpk/Build/Products/Debug/test

不是你想要的。但是当应用程序从其他地方运行时,您根本不会获得文件。

这是因为您没有像在第一个代码中那样指定有效路径。

所以这次应该是例如使用 Users Applications Support 目录

 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSApplicationSupportDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"test"];

  BOOL success = [NSKeyedArchiver archiveRootObject:self.arrayHit toFile:filePath];
      NSLog(@"success %hhd",success)

但我真的建议您阅读基础知识和其他文档,以便更好地理解您正在编写的内容

我刚找到 Start Developing Mac Apps Today发布于 2013 年,看起来像是 Apple 让人们在学习中抢先一步的新方式。看起来是个不错的起点

它包括

Read This Article Now: Acquire Foundational Programming Skills describes the basic tasks in Objective-C programming. The concepts explained in this article are essentially the same for Mac and iOS development.

这就是我们在这里使用的。

但我建议你从头开始..

关于ios - 将 NSMutableArray 保存到文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22768227/

相关文章:

iphone - 使用适用于 Iphone 的 DropBox SDK 从 UIImageView 上传图像

ios - 无法将类型 'Swift.Optional<Swift.AnyObject>' (0x7f9d44715db0) 的值转换为 'NSArray' (0x60000004f4f8)

ios - 一起使用 TouchDB 和 FMDB 包装器时出现重复符号错误

ios - iOS 应用预售

ios - 从另一个应用程序连接到蓝牙设备

iphone - UIWebView 和 NSURLCache 的关系很麻烦

ios - 如何向 MKPointAnnotation 添加按钮?

jquery - 在 iOS 设备上的 iframe 中不触发点击/点击事件

javascript - uiwebview 缩放文本

具有辅助功能的 iOS UITableView 编辑