objective-c 写入字典到CSV文件但不覆盖原数据
时间: 2024-10-26 09:16:07 浏览: 24
在Objective-C中,如果你想将字典写入CSV文件并且避免覆盖已有数据,你可以采用追加(appending)模式打开文件,而不是直接覆盖。这里是一个基本的步骤:
1. 首先,你需要导入Foundation框架,因为它包含了`NSFileManager`和`NSString`等用于文件操作的类。
```objective-c
#import <Foundation/Foundation.h>
```
2. 定义一个函数来写入CSV数据,假设你已经有了一个字典数组 (`NSArray<NSDictionary *> *dicts`) 和 CSV文件路径 (`NSString *filePath`):
```objective-c
- (void)appendDictsToCSV:(NSArray<NSDictionary *> *)dicts filePath:(NSString *)filePath {
NSError *error = nil;
// 创建一个CSV字符串
NSMutableString *csvString = [NSMutableString string];
for (NSDictionary *dict in dicts) {
NSArray *keys = dict.allKeys;
for (int i = 0; i < keys.count; i++) {
NSString *key = keys[i];
id value = dict[key];
if (i > 0) csvString = [csvString stringByAppendingString:@","];
// 对非字符串值进行转换(例如数字)
NSString *formattedValue = value == [NSNull null] ? @"" : [value description];
csvString = [csvString stringByAppendingFormat:@"%@%@", key, formattedValue];
}
csvString = [csvString stringByAppendingString:@"\n"];
}
// 追加到文件
NSOutputStream *outputStream = [[NSOutputStream alloc] initToFileAtPath:filePath append:YES];
if (!outputStream) {
NSLog(@"Failed to open output stream: %@", error.localizedDescription);
return;
}
const char *utf8Data = [csvString cStringUsingEncoding:NSUTF8StringEncoding];
NSInteger bytesWritten = [csvString lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
if ([outputStream open]) {
uint8_t buffer[4096];
while (bytesWritten > 0) {
NSInteger written = [outputStream write:&utf8Data bytes:bytesWritten];
if (written <= 0) {
NSLog(@"Error writing to file: %@", error.localizedDescription);
break;
}
utf8Data += written;
bytesWritten -= written;
}
[outputStream close];
} else {
NSLog(@"Failed to open file for appending: %@", error.localizedDescription);
}
}
```
3. 调用这个函数,并传入字典数组和文件路径:
```objective-c
NSArray<NSDictionary *> *myDictionaries = ...; // 你的字典数组
NSString *filePath = @"path_to_your_file.csv";
[self appendDictsToCSV:myDictionaries filePath:filePath];
```
阅读全文