将csv文件解析为NSMutableArray

时间:2014-12-18 00:54:00

标签: ios objective-c csv

我知道有关如何在目标c中读取.csv文件然后将其传递给NSMuatbleArray的说明,但是当我将它分配给mutableArray时我遇到了问题。我花了几个小时在线检查并尝试修复它,但没有任何帮助。

这是我的目标c代码:

NSError *err;
NSString *filePath = [NSString stringWithContentsOfFile:@"/users/Mike/Desktop/Book1.csv" encoding:NSUTF8StringEncoding error:&err];

NSString *replace = [filePath stringByReplacingOccurrencesOfString:@"\"" withString:@""];
NSString *something = [replace stringByReplacingOccurrencesOfString:@"," withString:@"\n"];

NSMutableArray *columns = [[NSMutableArray alloc] initWithObjects:[something componentsSeparatedByString:@"\n"], nil];

NSLog(@"%@", filePath);
NSLog(@"%@", something);
NSLog(@"%@", columns);

这是输出:

My App[1854:54976] Kitchen,Bathroom,Dinning Room,Living Room
My App[1854:54976] Kitchen
Bathroom
Dinning Room
Living Room

My App[1854:54976] (
        (
        Kitchen,
        Bathroom,
        "Dinning Room",
        "Living Room"
    )
)

问题是数组的输出带有逗号和引号,我删除了。 我需要的是阵列"列"像字符串一样出来"东西"。

更新

我带走了两个字符串"替换"和"某事"并将数组切换到:

collumns = [[NSMutableArray alloc] initWithObjects:[filePath componentsSeparatedByString:@","], nil];

现在我无法将其加载到表格视图中。这是我的代码。

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"firstCell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];

    cell.textLabel.text = [columns objectAtIndex:indexPath.row];
    return cell;
}

该应用程序因未解释的原因崩溃,但当我手动创建另一个阵列时,它可以正常工作。 这个有效:

NSMutableArrayrow = [[NSMutableArray alloc] initWithObjects:@"First", @"Second", nil];

1 个答案:

答案 0 :(得分:2)

您的代码有点混乱,并且包含一个错误,导致您无法解释的括号。

  • 为什么在没有引号的情况下用引号替换引号 源数据?
  • 为什么要用换行符替换逗号,然后将字符串拆分为 换行符上的一个字符串数组(摆脱了这一行 彻底打破)?为什么不直接将字符串拆分为数组 逗号并跳过中间步骤?
  • 最后,最严重的是,方法initWithObjects想要一个 逗号分隔的对象集,然后是零。你正在传递它 数组,没有。所以你得到的结果是可变的 包含单个对象的数组,一个不可变数组。这是 几乎可以肯定你想要的东西。

这一行:

NSMutableArray *columns = 
  [[NSMutableArray alloc] initWithObjects:
    [something componentsSeparatedByString:@"\n"], nil];

......错了。

你可以像这样使用initWithObjects:

NSMutableArray *columns = 
  [[NSMutableArray alloc] initWithObjects: @"one", @"two", @"three", nil];

注意我是如何传入以逗号分隔的对象列表,然后是nil。您对initWithObjects的使用是传入一个对象,一个数组,然后是一个nil。你不会得到一个包含源数组中对象的可变数组 - 你将得到一个包含你的起始不可变数组的可变数组。

应该这样写:

NSMutableArray *columns = [[something componentsSeparatedByString:@"\n"] 
  mutableCopy];

或者更好的是,分两步完成,所以很清楚:

NSArray *tempArray = [something componentsSeparatedByString:@"\n"];
NSMutableArray *columns = [tempArray mutableCopy];