17

SQLファイルからcsvファイルにデータを書き込みたい。配列内のSQLファイルからすべてのデータを収集し、forループを使用してデータを.csvファイルに追加および書き込みています。ただし、データは1行で表示されているようですが、新しい行を作成するために新しい行に移動することはありません。参考までに使用しました。これは私のコードです:

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

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

    NSString *writeString;    
    for (int i=0; i<[dataArray count]; i++) {        
        writeString = [NSString stringWithFormat:@"%@, %@, %@, %@, %0.2f,",[[dataArray objectAtIndex:i]dates],[[dataArray objectAtIndex:i] time],[[dataArray objectAtIndex:i] category],[[dataArray objectAtIndex:i]place],[[dataArray objectAtIndex:i] amount]];        
        NSLog(@"writeString :%@",writeString);        
        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:[writeString dataUsingEncoding:NSUTF8StringEncoding]];      
    }    
}
4

4 に答える 4

37

ループを通過するたびにファイルを書き換えるため、これは1行しか書き込みません。writeDataループが完了するまでファイルにアクセスしないことをお勧めします。次のように NSMutableString も使用します。

- (IBAction)saveAsFileAction:(id)sender {

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

    NSMutableString *writeString = [NSMutableString stringWithCapacity:0]; //don't worry about the capacity, it will expand as necessary

    for (int i=0; i<[dataArray count]; i++) {
        writeString = [writeString appendString:[NSString stringWithFormat:@"%@, %@, %@, %@, %0.2f, \n",[[dataArray objectAtIndex:i]dates],[[dataArray objectAtIndex:i] time],[[dataArray objectAtIndex:i] category],[[dataArray objectAtIndex:i]place],[[dataArray objectAtIndex:i] amount]]]; //the \n will put a newline in
      }
    }

    //Moved this stuff out of the loop so that you write the complete string once and only once.
    NSLog(@"writeString :%@",writeString);

    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:[writeString dataUsingEncoding:NSUTF8StringEncoding]];
}    
于 2012-04-12T07:20:48.633 に答える
5
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory , NSUserDomainMask, YES); 
    NSString *documentsDir = [paths objectAtIndex:0];
    NSString *root = [documentsDir stringByAppendingPathComponent:@"customers.csv"];

    NSString *temp;

    temp = [NSString stringWithFormat:@"%@", [arrCustomersName objectAtIndex:0]];

    for (int i = 1; i < [arrCustomersName count]; i++) {

        temp = [temp stringByAppendingFormat:@", %@", [arrCustomersName objectAtIndex:i]];
    }

    [temp writeToFile:root atomically:YES encoding:NSUTF8StringEncoding error:NULL];
于 2013-03-26T13:07:34.537 に答える
1
 // For CSV File :
       NSMutableString *stringToWrite = [[NSMutableString alloc] init];
 [stringToWrite appendString:[NSString stringWithFormat:@"First Name,Last Name,Full Name,Phone Number, Email,Job, organizationName,Note\n\n"]];
 dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
      for(int i = 0 ;i<[Contact count];i++)     {
           [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"firstName"] ]];
           [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"lastName"] ]];
           [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact valueForKey:@"userName"] objectAtIndex:i]]];
           [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"phoneNumber"] ]];
           [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"emailAddress"] ]];
           [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact objectAtIndex:i] valueForKey:@"jobTitle"] ]];
           [stringToWrite appendString:[NSString stringWithFormat:@"%@,",[[Contact  objectAtIndex:i] valueForKey:@"organizationName"] ]];
           [stringToWrite appendString:[NSString stringWithFormat:@"%@\n",[[Contact objectAtIndex:i] valueForKey:@"note"] ]];
      }
      dispatch_async(dispatch_get_main_queue(), ^(void) {
           NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
           NSString *documentDirectory=[paths objectAtIndex:0];
           NSString *strBackupFileLocation = [NSString stringWithFormat:@"%@/%@", documentDirectory,@"ContactList.csv"];
           [stringToWrite writeToFile:strBackupFileLocation atomically:YES encoding:NSUTF8StringEncoding error:nil];
      });
 });
于 2016-12-29T12:46:47.937 に答える