2013-07-20 66 views
0

(故事板圖像) http://i.stack.imgur.com/DUZ12.png地址簿數據持久性?

有3個文本字段,其中用戶輸入的數據,並將其保存。在打開應用程序時,如果有任何保存數據,則先前的輸入顯示在文本字段內。問題是,只有一組數據,而它需要是一個包含多個人信息的數組。我想創建一個帶名稱單元格的導航控制器,點擊它們就會顯示相關的聯繫信息。

viewcontroller.h

@interface ArchiveViewController : UIViewController 
    @property (strong, nonatomic) IBOutlet UITextField *name; 
    @property (strong, nonatomic) IBOutlet UITextField *address; 
    @property (strong, nonatomic) IBOutlet UITextField *phone; 
    @property (strong, nonatomic) NSString *dataFilePath; 
    - (IBAction)saveData:(id)sender; 
    @end 

viewcontroller.m

@interface ArchiveViewController() 

@end 

@implementation ArchiveViewController 

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
NSFileManager *filemgr; 
NSString *docsDir; 
NSArray *dirPaths; 

filemgr = [NSFileManager defaultManager]; 

// Get the documents directory 
dirPaths = NSSearchPathForDirectoriesInDomains(
    NSDocumentDirectory, NSUserDomainMask, YES); 

docsDir = dirPaths[0]; 

// Build the path to the data file 
_dataFilePath = [[NSString alloc] initWithString: [docsDir 
     stringByAppendingPathComponent: @"data.archive"]]; 

// Check if the file already exists 
if ([filemgr fileExistsAtPath: _dataFilePath]) 
{ 
     NSMutableArray *dataArray; 

     dataArray = [NSKeyedUnarchiver 
      unarchiveObjectWithFile: _dataFilePath]; 

     _name.text = dataArray[0]; 
     _address.text = dataArray[1]; 
     _phone.text = dataArray[2]; 
} 

} 

- (void)didReceiveMemoryWarning 
{ 
    [super didReceiveMemoryWarning]; 
    // Dispose of any resources that can be recreated. 
} 

- (IBAction)saveData:(id)sender { 
    NSMutableArray *contactArray; 

    contactArray = [[NSMutableArray alloc] init]; 
    [contactArray addObject:self.name.text]; 
    [contactArray addObject:self.address.text]; 
    [contactArray addObject:self.phone.text]; 
    [NSKeyedArchiver archiveRootObject: 
     contactArray toFile:_dataFilePath]; 

} 
@end 

謝謝您的時間。

回答

0

而不是使用其中包含3個文本元素的數組,並使用NSKeyedArchiver,將其中包含字典的數組與其保存爲writeToFile:atomically:。這將使用數組作爲'條目'列表而不是字段列表,並將數據保存在plist而不是二進制文件中。

現在,當您讀取數組時,您可以顯示條目的表視圖(例如只顯示名稱),然後當您顯示歸檔視圖時,可以將控制器傳遞給適當的字典。

爲了保存,最好使用委託將編輯傳遞迴主控制器。但它也可以直接完成(需要詳細控制器中的更多知識)或通知。

+0

出於好奇,你認爲創建類似地址簿的應用程序的方法是一個好方法嗎? –

+0

你還沒有給出很多關於整體結構的細節。這將是一個導航控制器中的表格視圖,我想說的是正確的。在iPad上,您可以使用集合視圖來提供更有趣的界面...... – Wain