2011-03-21 101 views
0

我有一個CSV文件,包含四個字段,「Woonplaats」,「Gemeente」,「Provincie」,「Latitude」和「Longitude」。NSScanner和一個CSV文件

值的示例:

Graveland,Wijdemeren,北荷蘭省,52.24412000,5.12150000

使用下面的代碼,我得到了我的文本字符串,然後我要救它在陣列中。我應該如何使用NSScanner從這個字符串獲取數據並保存在包含字典的數組中?

NSString *filePath = [[NSBundle mainBundle] pathForResource:@"cities" ofType:@"csv"]; 
NSString *myText = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil ]; 
NSScanner *scanner = [NSScanner scannerWithString:myText]; 
[scanner setCharactersToBeSkipped:[NSCharacterSet characterSetWithCharactersInString:@"\n ,"]]; 
NSMutableArray *newPoints = [NSMutableArray array];   

回答

1

我相信這就是你要找的。我用Dan Wood論壇帖子,並根據您的需要進行了修改。

#import <Foundation/Foundation.h> 

int main (int argc, const char * argv[]) 
{ 
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; 

    // insert code here... 

    NSString *path [email protected]"cities.csv"; 
    NSError *error; 
    NSString *stringFromFileAtPath = [[NSString alloc] 
             initWithContentsOfFile:path 
             encoding:NSUTF8StringEncoding 
             error:&error]; 

    NSMutableDictionary *lineDict = [NSMutableDictionary dictionary]; 
    NSArray *lines = [stringFromFileAtPath componentsSeparatedByString:@"\n"]; 
    NSEnumerator*theEnum = [lines objectEnumerator]; 
    NSArray *keys = nil; 
    int keyCount = 0; 
    NSString *theLine; 

    while (nil != (theLine = [theEnum nextObject])) 
    { 
     if (![theLine isEqualToString:@""] && ![theLine hasPrefix:@"#"]) // ignore empty lines and lines that start with # 
     { 
      if (nil == keys) // Is keys not set yet? If so, process first real line as list of keys 
      { 
       keys = [theLine componentsSeparatedByString:@","]; 
       keyCount = [keys count]; 
      } 
      else // A data line 
      { 
       NSArray *values = [theLine componentsSeparatedByString:@","]; 
       int valueCount = [values count]; 
       int i; 

       for (i = 0 ; i < keyCount && i < valueCount ; i++) 
       { 
        NSString *value = [values objectAtIndex:i]; 
        if (nil != value && ![value isEqualToString:@""]) 
        { 
         [lineDict setObject:value forKey:[keys objectAtIndex:i]]; 
        } 
       } 
      } 
     } 
    } 

    for (id key in lineDict) 
    { 
     NSLog(@"key: %@, value: %@", key, [lineDict objectForKey:key]); 
    } 

    [pool drain]; 
    return 0; 
} 

,輸出是:

2011-07-13 20:02:41.898 cities[5964:903] key: Latitude, value: 52.24412000 
2011-07-13 20:02:41.900 cities[5964:903] key: Provincie, value: Noord-Holland 
2011-07-13 20:02:41.900 cities[5964:903] key: Longitude, value: 5.12150000 
2011-07-13 20:02:41.901 cities[5964:903] key: Gemeente, value: Wijdemeren 
2011-07-13 20:02:41.902 cities[5964:903] key: Woonplaats, value: Graveland 
相關問題