CSVからPLISTに変換する方法
以前、PLISTからCSVに変換する方法という記事を書いた。
その記事内で、
CSVからPLISTに変換するには、つつみさんの記事(http://d.hatena.ne.jp/shu223/20110511/1305129443)の方法や、CSV2PlistというMacアプリ(http://sheepapp.com/app/CSV2Plist/)で解決できる。
と書いたが、なんだかんだ、CSVからPLISTに変換する方法も自分でObj-cで書きたくなった。
ということで、さっそくコードを。
前提条件としては、
(1)変換前のCSVの形式は、下記のようなもの。
no,name,hp,mp
0,suzuki,32,23
1,osamu,27,34
2,desu,21,45
(文字コードは、自分の環境でデフォルトでShift_Jisだった。Mac Excelでcsv保存すると、デフォルトShift_Jisになるはず)
(2)アプリのDocuments/ディレクトリ以下に変換したいCSVをいれといて、同じディレクトリにPLISTを吐き出す。
NSError *error; NSString *filePath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"prologue.csv"]; NSString *text = [NSString stringWithContentsOfFile:filePath encoding:NSShiftJISStringEncoding error:&error];//NSUTF8StringEncoding if (error) { NSLog(@"error:%@",error); } NSMutableArray *outputArray = [NSMutableArray array]; NSArray *lines = [text componentsSeparatedByString:@"\r"];// @"\n" NSString *keysStr = [lines objectAtIndex:0]; NSArray *keys = [keysStr componentsSeparatedByString:@","]; for (NSInteger i = 1;i<[lines count];i++ ) { NSString *itemsStr = [lines objectAtIndex:i]; NSArray *items = [itemsStr componentsSeparatedByString:@","]; NSMutableDictionary *content = [NSMutableDictionary dictionary]; for (NSInteger k=0; k<[items count]; k++) { NSString *item = [items objectAtIndex:k]; NSString *key = [keys objectAtIndex:k]; [content setObject:item forKey:key]; } [outputArray addObject:content]; } NSString *fileName = @"hogehoge.plist"; BOOL result = [outputArray writeToFile:[[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:fileName] atomically:YES]; NSString *msg; if (!result) { msg = @"ファイルの書き込みエラー"; }else{ msg = @"ファイルの書き込み成功"; } UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"" message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; [alert show];
検索かけたら、
CSVをPlistに変換する - Qiita
という記事をみつけたけど、思った通りの動きをしなかったので、ちょいとアレンジした感じ。