iphone - 在 Documents 文件夹中写入文件列表并将其保存在内存中

标签 iphone ios nsarray save

我有几个文件要保存在“文档”文件夹中,此文件列表放入一个可变数组中。这些文件必须保留在 iPhone 应用程序的内存中,同时也已关闭。第一个文件已保存,但是当我更改 View Controller 然后返回时,可变数组变为空。如何将内存中的数据保存在 Documents 文件夹中?

在DetailExpViewController.h

  //....
  @property (nonatomic, strong)NSMutableArray *arrayFavorites;
  @property (nonatomic, assign)BOOL existsArray;
  //....
  @end

在DetailExpViewController.m

- (void)viewDidLoad
 {
      //.....
      if (!self.existsArray){
          /*when I load the view controller this array is always nil even 
            has already  been created*/

           self.arrayFavorites =[[NSMutableArray alloc]init];
     }else{
          NSLog(@"The array exists");
      }
      //....
 }

 -(void) addFavorites:(id)sender{

     //.....
   NSArray *paths = NSSearchPathForDirectoriesInDomains
  (NSDocumentDirectory, NSUserDomainMask, YES);
   NSString *documentsDirectory = [paths objectAtIndex:0];

   NSString * text= [NSString stringWithFormat:@"%@.txt",self.name];
   NSString * documentsPath = [documentsDirectory stringByAppendingPathComponent: text];

   [self.arrayFavorites addObject:text];
   [self.arrayFavorites writeToFile:documentsPath atomically:YES];
   self.existsArray=YES;

   for (id obj in self.arrayFavorites) {

    NSLog(@"%@", self.arrayFavorites);
    //only writes the file at the time, then it is deleted

  }

}

最佳答案

你可以将 NSArray 保存在文档目录中,例如 this .

注意:保存检索文件名保持相同

它还可以从doc dir轻松检索保存的数组

编辑:如果数据复杂且庞大,最好使用SQLITE


编辑:在 View Controller 的添加到收藏夹按钮中单击事件:

 //check favourite saved in doc dir
 if(!saved) //not saved
   //NSMutableArray has not data first time
   //[NSMutableArray addObject:newFavourite];
   //save new data in doc dir
 else // saved
   //firstly retrieve data from doc dir as NSMutableArray
   //[NSMutableArray addObject:newFavourite];
   //Now save again NSMutableArray in doc dir.

按照操作,这些说明文件将永久保留在文档文件夹中。

关于iphone - 在 Documents 文件夹中写入文件列表并将其保存在内存中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14192419/

相关文章:

iphone - 比较两个数组

objective-c - UITextField 设置可见?

ios - UITableview 滚动改变图像,UITableview 滚动问题

ios - 将标记添加到 GMSMapView subview ios

ios - 如何创建和排序浮点字典数组

objective-c - 一步复制并排序 NSArray

objective-c - 访问另一个 NSMutableArray 中对象的 NSMutableArray(即嵌套对象访问)

iphone - 在另一个数组的基础上对数组进行排序

iphone - 如何在 iPhone 中安全地存储 SQLite 数据库..?

iphone - iOS 版本中缺少 Comic Sans