[英]saving NSMutable Array Data
我有一個使用NSMutableArray填充的UITableView。 我正在使用xcode 4.2
NSMutable數組中的數據保留,以防萬一我切換了應用程序,但在以下兩種情況下它們被擦除了:1-用戶切換視圖並返回。
2-該應用程序已完全關閉(即用戶雙擊“主要”按鈕並將其從正在運行的應用程序列表中刪除)
這是我正在使用的代碼
-(NSString *)dataFilePath{
NSString *dataFilePath;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
dataFilePath = [documentDirectory stringByAppendingPathComponent:@"Test App-Info.plist"];
return dataFilePath;
}
-(void)saveData{
[NSKeyedArchiver archiveRootObject:[data copy] toFile:[self dataFilePath]];
}
- (void)loadData
{
data = [NSKeyedUnarchiver unarchiveObjectWithFile:self.dataFilePath];
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
...
//saving the history
NSArray *archivedArray =[NSKeyedUnarchiver unarchiveObjectWithFile:[self dataFilePath]];
if (archivedArray == nil) {
data = [[NSMutableArray alloc] init];
}
else {
[self loadData];
[mainTableView reloadData];
}
}
如果我錯過了什么,請告訴我
謝謝
編輯:
保存數據功能在兩個位置加載:1-我正在開發的應用程序掃描QR碼,因此在以下功能中調用保存數據:
- (void) imagePickerController: (UIImagePickerController*) reader
didFinishPickingMediaWithInfo: (NSDictionary*) info
{
....
id<NSFastEnumeration> results =
[info objectForKey: ZBarReaderControllerResults];
ZBarSymbol *symbol = nil;
for(symbol in results){
// EXAMPLE: just grab the first barcode
break;
}
if(!symbol)
return;
// EXAMPLE: do something useful with the barcode data
theBarcodeString = symbol.data;
//adding the string to the list
[data addObject:theBarcodeString];
[self saveData];
[mainTableView reloadData];
[self endText];
stringLabel.text=theBarcodeString;
...
}
編輯數據時也會調用它:
-(IBAction)editTable{
UIBarButtonItem *leftItem;
[mainTableView setEditing:!mainTableView.editing animated:YES];
if (mainTableView.editing) {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(editTable)];
}
else {
leftItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editTable)];
}
[self saveData];
[mainTableView reloadData];
}
您需要研究以下調用:
applicationDidEnterBackground
applicationWillEnterForeground
applicationDidBecomeActive
applicationWillTerminate
它們都是UIApplication的方法。 您的需求將決定上述存儲區中的哪一個,並根據何時發生恢復數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.