Created
January 12, 2013 16:31
-
-
Save thata/4519094 to your computer and use it in GitHub Desktop.
keyとvalueからなるタブ区切りの文字列を読み込んでdictionaryへセットするサンプル
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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