LoginSignup
19
19

More than 5 years have passed since last update.

Objective-CでCSVをパースする

Last updated at Posted at 2014-04-24

NTYCSVTableというライブラリを使うと簡単にパースできる。名前の通りCSVをテーブル構造のオブジェクトにパースしてくれるので直感的に扱いやすい。RubyのCSV::Tableクラスを参考に開発されている。

インストール

CocoaPodsに公開されているのでPodfileにこのように書いてpod installすればインストールできる。

Podfile
pod "NTYCSVTable"

使い方

このようなCSVのパースを想定する。

users.csv
id,name,age
1,Alice,18
2,Bob,19
3,Charlie,20

これをパースするにはこうすればいい。

NSURL *csvURL = [NSURL URLWithString:@"users.csv"];
NTYCSVTable *table = [[NTYCSVTable alloc] initWithContentsOfURL:csvURL];

// Rows
NSArray *rows = table.rows;
NSArray *headers = table.headers;    //=> @[@"id", @"name", @"age"]
NSDictionary *alice = table.rows[0]; //=> @{@"id": @1, @"name": @"Alice", @"age": @18}
NSDictionary *bob = table.rows[1];   //=> @{@"id": @2, @"name": @"Bob", @"age": @19}

// Columns
NSDictionary *columns = table.columns;
NSArray *names = table.columns[@"name"]; //=> @[@"Alice", @"Bob", @"Charlie"]
NSArray *ages = table.columns[@"age"];   //=> @[@18, @19, @20]

また、あるヘッダーに特定の値を持つ列を検索するためにこのようなメソッドも用意されている。

[table rowsOfValue:@1 forHeader:@"id"];  //=> @[@{@"id": @1, @"name": @"Alice", @"age": @18}]
[table rowsOfValue:@20 forHeader:@"age"] //=> @[@{@"id": @3, @"name": @"Charlie", @"age": @20}]

以上、ステマでした。

19
19
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
19
19