有这么一个需求,需要将程序中的数据信息写到csv文件中,可以使用excel等软件方便浏览。
总结以下实现过程。
使用到CoreData,界面布局如下:
在.m文件中声明私有方法:
- (void)createFile:(NSString *)fileName;
- (void)exportCSV:(NSString *)fileName;
- (NSArray *)queryStudents;
关联方法:
- (IBAction)inputData:(id)sender {
AppDelegate *app = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Student *stu = (Student *)[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
stu.name = self.nameTextField.text;
stu.num = self.numTextField.text;
NSError *error = nil;
[context save:&error];
self.nameTextField.text = @"";
self.numTextField.text = @"";
}
- (IBAction)makeCSV:(id)sender {
NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDirectory, YES);
NSString *docementDir = [documents objectAtIndex:0];
NSString *filePath = [docementDir stringByAppendingPathComponent:@"student.csv"];
NSLog(@"filePath = %@", filePath);
[self createFile:filePath];
[self exportCSV:filePath];
}
私有方法:
- (void)createFile:(NSString *)fileName {
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager removeItemAtPath:fileName error:nil];
if (![fileManager createFileAtPath:fileName contents:nil attributes:nil]) {
NSLog(@"不能创建文件");
}
}
- (void)exportCSV:(NSString *)fileName {
NSOutputStream *output = [[NSOutputStream alloc] initToFileAtPath:fileName append:YES];
[output open];
if (![output hasSpaceAvailable]) {
NSLog(@"没有足够可用空间");
} else {
NSString *header = @"学好,姓名\n";
const uint8_t *headerString = (const uint8_t *)[header cStringUsingEncoding:NSUTF8StringEncoding];
NSInteger headerLength = [header lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
NSInteger result = [output write:headerString maxLength:headerLength];
if (result <= 0) {
NSLog(@"写入错误");
}
NSArray *students = [self queryStudents];
for (Student *stu in students) {
NSString *row = [NSString stringWithFormat:@"%@,%@\n", stu.num, stu.name];
const uint8_t *rowString = (const uint8_t *)[row cStringUsingEncoding:NSUTF8StringEncoding];
NSInteger rowLength = [row lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
result = [output write:rowString maxLength:rowLength];
if (result <= 0) {
NSLog(@"无法写入内容");
}
}
[output close];
}
}
- (NSArray *)queryStudents {
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:self.managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
fetchRequest.entity = entity;
NSArray *students = [self.managedObjectContext executeFetchRequest:fetchRequest error:nil];
return students;
}