2011-09-03 85 views
0

我到處搜索,並嘗試了很多代碼,但似乎沒有任何工作對我來說。我需要做的就是加載(在viewDidLoad上)一個文本字段並在按下按鈕時保存它。我將如何保存並加載UITextField?

什麼是最簡單這樣做的方法?我正與一個窗口應用程序的工作,我沒有一個視圖控制器(這可能有所作爲?)

感謝,

詹姆斯

+0

你說'保存'。保存是什麼意思?你需要永久保存這些數據嗎? –

+0

這就像一個筆記應用程序,我需要用戶能夠保存文本字段,當他們關閉並自動打開應用程序,而不必做任何事情。 – pixelbitlabs

+0

而我得到這個錯誤代碼與一個推薦的方法:http://pastie.org/2475070我跟着本教程:http://twitc.com/Pkon7swrQ – pixelbitlabs

回答

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,請檢查網絡。但是,我猜將來會對你有很大的幫助。我認爲這將是最靈活的,因爲它也允許你創建關係數據庫。

+0

這很難嗎?這需要多長時間? – pixelbitlabs

+0

我忘了提及:保存:在這種情況下,使用「UPDATE」語句並檢查SQLITE_DONE。上面提到的方法是我將放在viewDidLoad方法中的方法。爲了初始化項目中的數據庫,互聯網上有大量信息。 – Trace

+0

不長,相信我 - 你會在一天結束前得到它;事實上這很容易。這裏有一個基於視圖的應用程序教程:http://www.techotopia.com/index.php/An_Example_SQLite_based_iPhone_Application但是我也建議你查看更多的網站,以防你沒有立即理解一些細節。 – Trace

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

你好,謝謝你! .rtf文件是否可以將數據保存到? – pixelbitlabs

+0

它不工作,當按下保存按鈕時,我得到一個NSException錯誤... – pixelbitlabs

+0

是的,只要你編碼正確。 UTF-8正常工作。 –

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除外)。
爲每個要存儲值的字段使用不同的鍵。
這也可以用來存儲應用程序配置/選項/等