0

我有几个文件要保存在 Documents 文件夹中,这个文件列表放在一个可变数组中。文件必须保留在 iPhone 应用程序的内存中也关闭。第一个文件已保存,但是当我更改视图控制器然后返回时,可变数组变为空。如何将数据保存在 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

  }

}

4

1 回答 1

1

可以这样。save NSArray_Document Directory

saving还有retrieving filename遗体same

它也easy retrieve saved array来自doc dir

编辑:如果更好data用。complex and largeSQLITE


编辑:在view Controller's添加到favourite按钮中单击event

 //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.

通过following这些instruction文件保留permanentlyDocuments folder.

于 2013-01-07T08:53:26.040 回答