2009-12-24 38 views
0

如果我希望用戶能夠編輯條目到帶有數字數據的表格中,(用戶將點擊一個表格單元格,然後在該子視圖中,他們將輸入一個數字,然後返回到主表視圖),我想我只是將條目添加到NSMutabaleArray。如果是這樣,當用戶離開應用程序時,那些值是否仍然存在?如果他們是,我是否也需要一個清除表格的方法來釋放數組?謝謝。NSArray,UITableView

回答

2

您的應用程序的數據不會自動保存。

如果您的數據量很少,則可以將數組等集合寫出到應用程序Documents目錄中的Property List(plist)文件中。

如果您有大量數據,我會推薦使用核心數據。

0

快速而骯髒的方法是使用NSKeyedArchiver將NSArray寫入文件。然後,當應用程序啓動時,您必須將文件中的數據讀回到您的NSArray中。

這裏有一個片段:

這得到文件的路徑:

- (NSString*)pathForDataFile 
{ 
    //Get the path of the Documents directory 
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString* documentsDirectory = [paths objectAtIndex: 0]; //Path to the documents directory 

    //Get the path to my file in /Documents 
    NSString* documentsPath = [documentsDirectory stringByAppendingPathComponent: 
           [NSString stringWithFormat: @"%@.plist", @"FileName"]]; 

    return documentsPath; 
} 

這些將保存和加載:

- (BOOL)saveDataToDisk 
{ 
    NSString* path = [self pathForDataFile]; 

    NSMutableDictionary* rootObject = [NSMutableDictionary dictionary]; 

    if (self.yourArray) 
     [rootObject setValue: self.powerListCollection.items forKey: kYourKey]; 

    [NSKeyedArchiver archiveRootObject: rootObject toFile: path]; 

    return YES; 
} 

-

- (BOOL)loadDataFromDisk 
{ 
    NSString* path = [self pathForDataFile]; 
    NSFileManager* manager = [NSFileManager defaultManager]; 

    if ([manager fileExistsAtPath: path]) 
    { 
     NSLog(@"Saved data found, loading data from %@", path); 

     NSMutableDictionary* rootObject = nil; 
     rootObject = [NSKeyedUnarchiver unarchiveObjectWithFile: path]; 

     NSArray* self.yourArray = [rootObject objectForKey: kYourKey]; 

    } 
    else 
    { 
     NSLog(@"No saved data, initializing objects with default values."); 
    } 

    return YES; 
} 

注意,你」我需要保留w憎恨你從objectForKey回來:

相關問題