如何获取数据写入文本文件?

时间:2013-03-19 13:57:36

标签: objective-c append

enter image description here这是我用于控制台输出的方法。如何输出到文本文件?

@implementation GetMoves
   - (id)initWithDevice:(Device *)device{
    if(self = [super init]){
          _device = device;
    }

    return self;
    }

- (void)Render{
    [super ClearConsole];

    printf("MOVES INFO\n");
    printf("==================================\n");

    NSArray* data = [_device GetData:NULL];

    NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

    if(data != nil){
        for(int i = 0; i < data.count; i++){
            DataPoint*          current = [data objectAtIndex:i];
            NSMutableString*    output  = [[NSMutableString alloc] init];

            [output appendFormat:@"%d",(i+1)];
            [output appendString:@" - "];
            [output appendString:[dateFormatter stringFromDate:current.RecordedAt]];
            [output appendString:@" - "];
            [output appendFormat:@"%d",current.StepCount];

            printf("%s\n", [output UTF8String]);
        }
    }
    else
        printf("No new data found on device.\n");

    printf("\n");
    printf("==================================\n");
    printf("\n");

    printf("Press ENTER to continue.");
    fgetc(stdin);
}
@end

1 个答案:

答案 0 :(得分:1)

您可以简单地写为:

    NSString *path = [@"~" stringByExpandingTildeInPath] ;
    //change your path here
    path=[path stringByAppendingString:@"/Documents/*REPORTS/"];

    //make a file name to write the data to using the documents directory:
    NSString *fileName = [NSString stringWithFormat:@"%@/TWCodeFile.txt",path];
    //create content - four lines of text
    NSString *content = @"The content of file, can be more by appending string.";
    //save content to the documents directory
    [content writeToFile:fileName
              atomically:NO
                encoding:NSStringEncodingConversionAllowLossy
                   error:nil];