代码之家  ›  专栏  ›  技术社区  ›  zebra

iphone,在沙盒中写入csv文件

  •  2
  • zebra  · 技术社区  · 14 年前

    根据你的经验,最好的方法是什么?

    编辑:

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    
    NSString *filename =@"test.csv";
    NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:filename];
    if(![[NSFileManager defaultManager] fileExistsAtPath: fullPathToFile]) {
                [[NSFileManager defaultManager] createFileAtPath: fullPathToFile contents:nil attributes:nil];
    }
    NSFileHandle *handle = [NSFileHandle fileHandleForWritingAtPath: fullPathToFile];
    NSString *data = [NSString stringWithFormat:@"%@,%@\n", latitudine.text, longitudine.text];
    [handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];
    

    它起作用了,但是。。。。每次调用writedata时,我只得到一行,没有附加。我想收集我的两个textlab的所有值。

    我的错在哪里?

    编辑2:

    是的,用这个代码找到解决方案:

    首先我创建了一个:

    - (NSString *)dataFilePath { 
        NSArray *paths = NSSearchPathForDirectoriesInDomains(
        NSDocumentDirectory, NSUserDomainMask, YES); 
        NSString *documentsDirectory = [paths objectAtIndex:0]; 
        return [documentsDirectory stringByAppendingPathComponent:@"myfile.csv"];
    

    }

    if (![[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]) {
        [[NSFileManager defaultManager] createFileAtPath: [self dataFilePath] contents:nil attributes:nil];
        NSLog(@"Route creato");
    
    }
    

    在我的一个方法中,我添加了检索数据的代码并附加到我的文件中:

    NSString *data = [NSString stringWithFormat:@"%@,%@ ", latitudine.text, longitudine.text]; 
    //create my data to append
    NSFileHandle *handle;
    handle = [NSFileHandle fileHandleForWritingAtPath: [self dataFilePath] ]; 
    //say to handle where's the file fo write
    [handle truncateFileAtOffset:[handle seekToEndOfFile]]; 
    //position handle cursor to the end of file
    [handle writeData:[data dataUsingEncoding:NSUTF8StringEncoding]];   
    //write data to with the right encoding
    

    1 回复  |  直到 14 年前
        1
  •  1
  •   tc.    14 年前

    如果你把它放在NSTemporaryDirectory()中,我认为它应该在app exit时被清除,如果是这样的话,可能值得检查一下。