我有几个文件要保存在“文档”文件夹中,此文件列表放入一个可变数组中。这些文件必须保留在 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/