如何获取数据的NSMutableString并将其放在不同的字符串中?

时间:2013-03-15 19:56:34

标签: objective-c core-data

我有一个包含数据的方法。我想创建一个该数据的字符串并将其写入文本文件。我创建了一个写入文本方法。如何将UpLoadDeviceData方法中的NSMutableString数据转换为我的writetotext方法的字符串*内容?以下是提取数据的方法:

这是我的写文字方法:

-(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 个答案:

答案 0 :(得分: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:的首选方法更糟糕,因为现在需要额外的工作来扫描格式字符串。

因此:最好的方法是逐个构造可变字符串,然后将其写入文件中。