Skip to content

Instantly share code, notes, and snippets.

@thata
Created January 12, 2013 16:31
Show Gist options
  • Save thata/4519094 to your computer and use it in GitHub Desktop.
Save thata/4519094 to your computer and use it in GitHub Desktop.
keyとvalueからなるタブ区切りの文字列を読み込んでdictionaryへセットするサンプル
NSString *data = [NSString stringWithContentsOfFile:@"/tmp/a"
encoding:NSUTF8StringEncoding
error:nil];
NSArray *lines;
// 行に分解
lines = [data componentsSeparatedByString:@"\n"];
// コメント行を取り除く
lines = [lines filteredArrayUsingPredicate:
[NSPredicate predicateWithBlock:^BOOL(NSString *line, NSDictionary *bindings) {
line = [line stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
if ([line length] == 0)
return NO;
if ([line hasPrefix:@"#"])
return NO;
return YES;
}]];
// 行をパースしてdictionaryへセット
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
for (NSString *line in lines) {
NSArray *keyAndValue = [line componentsSeparatedByString:@"\t"];
NSString *key = [keyAndValue objectAtIndex:0];
NSString *val = [keyAndValue objectAtIndex:1];
[dict setValue:val forKey:key];
}
NSLog(@"%@", dict);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment