我到处搜索并尝试了很多代码,但似乎没有什么对我有用。我需要做的就是加载(在viewDidLoad上)一个文本字段,并在按下按钮时保存它。
执行此操作的最简单方法是什么?我正在使用单个窗口应用程序,我没有视图控制器(这可能会有所不同?)
谢谢,
詹姆斯
答案 0 :(得分:1)
创建一个NSMutableDictionary作为属性和...
单击按钮时:
-(IBAction)buttonClicked:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *devicePath = [documentsDirectory stringByAppendingPathComponent:@"yourfile.txt"];
[self.dictionary setObject:self.textField.Text key:@"textField"];
[self.dictionary writeToFile:devicePath atomically:YES];
}
在viewDidLoad上,您可以通过以下方式获取文件的值:
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"youefile"
ofType:@"txt"];
self.dictioary = [[[NSMutableDictionary alloc] initWithContentsOfFile:filePath] autorelease];
答案 1 :(得分:1)
使用SQLite数据库:
- (IBAction)checkNotes {
sqlite3_stmt *statement;
const char *dbpath = [databasePath UTF8String];
if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
{
NSString *querySQL = [NSString stringWithFormat: @"SELECT Notes FROM NotesTable WHERE UserID = (\"%@\")", userID.text];
const char *query_stmt = [querySQL UTF8String];
sqlite3_prepare_v2(contactDB, query_stmt, -1, &statement, NULL);
if (sqlite3_step(statement) == SQLITE_ROW) {
NSString *notesField = [[NSString alloc] initWithUTF8String:(const char *) sqlite3_column_text(statement, 0)];
Notes.text = notesField;
[notesField release];
}else{
Status.text = @"Not found";
}
sqlite3_finalize(statement);
}
sqlite3_close(contactDB);
}
您可以玩一下,并根据您的需求调整此代码。 要实现SQLite3,请检查网络。但是我猜它将来会对你有所帮助。我认为这将是最灵活的,因为它还允许您创建关系数据库。
答案 2 :(得分:0)
使用专为此方案制作的 NSUserDefaults 类。
NSUserDefaults *defs = [NSUserDefaults standardUserDefaults];
// saving a NSString (you usually do this when the value is being submitted)
[defs setObject:textField.text forKey:@"aKey"];
[defs synchronize]; //this commits the new value - shouldn't be necessary because this is doe automatically, but just in case...
// loading a NSString (you usually do this on viewDidLoad)
testField.text = [defs objectForKey:@"aKey"];
该值存储在会话中 您也可以存储其他值类型(NSString除外) 对要存储值的每个字段使用不同的键 这也可用于存储应用配置/选项/等