2011-11-30 92 views
2

我有一个使用NSMutableArray填充的UITableView。我正在使用xcode 4.2保存NSMutable阵列数据

NSMutable阵列中的数据保持在我切换应用程序的情况下,但在以下两种情况下它被擦除: 1-用户切换视图并返回。

2的应用是completley关闭(即在主按钮,用户双击并运行应用程序的列表中删除)

这里要说的是,我使用

-(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]; 

} 
+0

因此,您从哪里保存数据? – Denis

+0

我可能是错的(我是App开发的新手)但根据代码,数据保存在Test App-Info.plist(项目plist)的dataFilePath中,是否应该将其更改为其他内容? – user1051935

+0

我的意思是你用什么方法调用saveData方法? – Denis

回答

1

你需要考虑以下呼叫:

applicationDidEnterBackground 
applicationWillEnterForeground 
applicationDidBecomeActive 
applicationWillTerminate 

他们UIApplic的所有方法通货膨胀。您的需求将决定上述哪个存储并根据应该何时发生恢复您的数据。

+0

我将文件的名称从“Test App-Info.plist”更改为“text.txt”,我发现没有写入任何内容....我不认为这是正常的,任何建议? – user1051935