简体   繁体   English

如何在iOS应用程序中保存文本数据?

[英]How can I save text data in an iOS application?

Using my application, the user will take a reading on my application, which will yield a string of text in this format: Reading, Date/Time, Gender, Age . 使用我的应用程序,用户将阅读我的应用程序,它将产生以下格式的文本字符串: Reading,Date / Time,Gender,Age Essentially, what I'm doing is taking this string and storing it in a table view in a different storyboard. 本质上,我正在做的是获取此字符串并将其存储在另一个演示图板中的表格视图中。 Then, every time the application is closed and reopened, the saved values should remain. 然后,每次关闭并重新打开应用程序时,保存的值都应保留。 The action of saving the string should be triggered by pressing a save button. 按下保存按钮即可触发保存字符串的操作。 How can this be implemented? 如何实现呢? Sample code is appreciated. 样例代码表示赞赏。

The easiest solution is to use NSUserDefaults: 最简单的解决方案是使用NSUserDefaults:

   // Add a string & save permanently
   NSMutableArray *savedStrings = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"SavedStrings"]];
   NSString *sampleString = @"Reading, 4 Feb 2017, 12:00, male, 30 years"; 
   [savedStrings addObject:sampleString];
   [[NSUserDefaults standardUserDefaults] setObject:savedStrings forKey:@"SavedString"];
   [[NSUserDefaults standardUserDefaults] synchronize];

    // At launch, get saved strings - use to populate the tableview
    NSMutableArray *savedStrings = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:@"SavedStrings"]];
I think this will help you...

//In firstViewController.m 
// Create strings to store the text info
NSString *firstName = [self.firstNameTF text];
NSString *lastName  = [self.lastNameTF text];
NSString *age = [self.ageTF text] ;
[defaults synchronize];

// Store the data with key.
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

[defaults setObject:firstName forKey:@"firstName"];
[defaults setObject:lastName forKey:@"lastname"];
[defaults setObject:age forKey:@"age"];

//In requiredViewController.m write this code.
// Get the stored data before the view loads
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

NSString *firstName = [defaults objectForKey:@"firstName"];
NSString *lastName = [defaults objectForKey:@"lastname"];
NSString *ageString = [defaults objectForKey:@"age"];

// Set saved data in UIElements.
self.firstNameLabel.text = firstName;
self.lastNameLabel.text = lastName;
self.ageLabel.text = age;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM