2013-03-15 36 views
-1

我有一個包含數據的方法。我想創建一個數據字符串並將其寫入文本文件。我創建了一個寫入文本方法。如何將UpLoadDeviceData方法中的NSMutableString數據獲取到我的寫入方法的字符串*內容中?這裏就是數據被拉到方法:如何獲取數據的NSMutableString並將其置於不同的字符串中?

這是我寫的文字方法:

-(void) writeToTextFile{ 

    //get mydocuments dir 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; 

    // System's date and timestamp 
    NSDate *currentDate = [NSDate date]; 
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
    [dateFormatter setDateFormat:@"MM.dd.YYYY HH:mm:ss"]; 
    NSString *dateString = [dateFormatter stringFromDate:currentDate]; 
    // NSLog(@"%@",dateString); 
+1

你的問題到底是什麼? – 2013-03-15 20:03:37

+0

當你的數據已經是一個字符串時,「string that data」是什麼意思? – Desdenova 2013-03-15 20:08:35

回答

0

您可以從可變的字符串做出非可變的字符串並寫入文件:

NSMutableString *theMutableString; 
NSString *nonMutableString = [NSString stringWithString:theMutableString]; 
[nonMutableString writeToFile:path atomically:YES encoding:NSUTF8Encoding error:nil]; 

或者更短,寫可變的字符串到文件:

[theMutableString writeToFile:path atomically:YES encoding:NSUTF8Encoding error:nil]; + 

如何有些話構建更長的字符串:

  • 如果要追加一個字符串到一個可變的字符串,使用appendString:

  • 效率低得多的方法是使用NSString類方法stringByAppendingString:。這會分配一個新的字符串併產生不必要的開銷。

  • 您的首選方法使用NSString類方法stringWithFormat:更糟,因爲現在需要額外的努力來掃描格式字符串。

因此:最好的方法是逐塊構建可變字符串,然後將其寫入文件中。

+0

是不是JSON已經是一個字符串?只要把它變成伊娃,你就可以在任何地方使用它。 – Mundi 2013-03-18 10:51:25

+0

看到我的答案:'appendString'。 – Mundi 2013-03-18 13:49:20

相關問題