LoginSignup
2
2

More than 5 years have passed since last update.

CSVをPlistに変換する

Posted at

NSArray・NSDictionaryの writeToFileメソッドを使うだけでPListに出力できます。

つまり手順としては
1. CSVファイルを読み込み、配列に格納する。
2. 配列をそのまま writeToFileする。
以上です。

//STEP 1
// CSVファイルを読み込む
NSString *filePath = @"/Users/hoge/hoge.csv";
NSString *text = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
NSMutableArray *marr = [NSMutableArray array];
// 改行文字で区切って配列に格納する
NSArray *lines = [text componentsSeparatedByString:@"\n"];

for (NSString *row in lines) {
    // コンマで区切って配列に格納する
    NSArray *items = [row componentsSeparatedByString:@","];
    if (items.count > 1) {
        NSDictionary *item = [[NSDictionary alloc]
                              initWithObjects:@[items[0],items[1]]
                              forKeys:@[@"name",@"class"]];
        [marr addObject:item];
    }
}

//STEP 2
// ホームディレクトリを取得
NSString *homeDir = NSHomeDirectory();
NSString *fileName = @"hoge.plist";
// 書き込み
BOOL result = [marr writeToFile:[homeDir stringByAppendingPathComponent:fileName]
                     atomically:YES];
if (!result) {
    NSLog(@"ファイルの書き込みエラー");
}else{
    NSLog(@"ファイルの書き込み成功");
}

2
2
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
2
2