阅读csv文件的ios
我有一个阅读csv文件的问题。 只显示csv文件的最后一行。 但是在我fetchedResultsController我有2行这是代码:
NSString * writeString; NSInteger i = 0; for (id object in [[self fetchedResultsController] fetchedObjects]) { NSString * object1 = [[object valueForKey:@"object1"] description]; NSString * object2 = [[object valueForKey:@"object2"] description]; NSString * object3 = [[object valueForKey:@"object3"] description]; NSString * object4 = [[object valueForKey:@"object4"] description]; writeString = [NSString stringWithFormat:@"%@, %@, %@, %@, \n", object1, object2, object3, object4]; i++; NSLog(@"%@ - %i", writeString, i); } NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString* savePath = [paths objectAtIndex:0]; savePath = [savePath stringByAppendingPathComponent:@"myfile.csv"]; [writeString writeToFile:savePath atomically:YES encoding:NSUTF8StringEncoding error:NULL]; NSLog(@"%@", savePath); NSString *fullPath = savePath; [self readTitleFromCSV:fullPath AtColumn:0];
和readTitleFromCSV方法:
-(void)readTitleFromCSV:(NSString*)path AtColumn:(int)column { NSMutableArray *titleArray=[[NSMutableArray alloc]init]; NSString *fileDataString=[NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil]; NSArray *linesArray=[fileDataString componentsSeparatedByString:@"\n"]; int k=0; for (id string in linesArray) if(k<[linesArray count]-1){ NSString *lineString=[linesArray objectAtIndex:k]; NSArray *columnArray=[lineString componentsSeparatedByString:@","]; [titleArray addObject:[columnArray objectAtIndex:column]]; k++; } NSLog(@"%@",titleArray); }
感谢您的帮助。
尝试使用NSMutableString而不是NSString:
NSMutableString *writeString = [NSMutableString string];
然后在for循环中:
[writeString appendString:[NSString stringWithFormat:@"%@, %@, %@, %@, \n", object1, object2, object3, object4]];