你如何将这个给定的NSString分成NSDictionary?

时间:2013-06-06 10:58:25

标签: objective-c nsmutablearray nsarray nsdictionary nsmutabledictionary

我从一些linux盒子里获得了一些数据,并希望将它放入NSDictionary中以便以后处理。

你如何将这个NSString变成NSDictionary,如下所示?

data
(
  bytes
  (
    60 ( 1370515694 )
    48 ( 812 )
    49 ( 300 )
    ...
   )
   pkt
   (
    60 ( 380698 )
    59 ( 8 )
    58 ( 412 )
    ...
   )
   block
   (
    60 ( 5 )
    48 ( 4 )
    49 ( 7 )
    ...
   )
   drop
   (
    60 ( 706 )
    48 ( 2 )
    49 ( 4 )
    ...
   )
   session
   (
    60 ( 3 )
    48 ( 1 )
    49 ( 2 )
    ...
   )
)

数据字符串如下所示:

//time bytes pkt block drop session
60 1370515694 380698 5 706 3
48 812 8 4 2 1
49 300 412 7 4 2
50 0 0 0 0 0
51 87 2 0 0 0
52 87 2 0 0 0
53 0 0 0 0 0
54 0 0 0 0 0
55 0 0 0 0 0
56 0 0 0 0 0
57 812 8 0 0 0
58 812 8 0 0 0
59 0 0 0 0 0
0 0 0 0 0 0
1 2239 12 2 0 0
2 0 0 0 0 0
3 0 0 0 0 0
4 0 0 0 0 0
5 0 0 0 0 0
6 0 0 0 0 0
7 2882 19 2 0 0
8 4906 29 4 0 0
9 1844 15 11 0 0
10 4210 29 17 0 0
11 3370 18 4 0 0
12 3370 18 4 0 0
13 1184 7 3 0 0
14 0 0 0 0 0
15 4046 19 3 0 0
16 4956 23 3 0 0
17 2960 18 2 0 0
18 2960 18 2 0 0
19 1088 6 2 0 0
20 0 0 0 0 0
21 3261 17 3 0 0
22 3261 17 3 0 0
23 1228 6 2 0 0
24 1228 6 2 0 0
25 2628 17 2 0 0
26 4688 26 3 0 0
27 1752 13 5 0 0
28 3062 21 5 0 0
29 174 2 2 0 0
30 96 1 1 0 0
31 4351 23 5 0 0
32 0 0 0 0 0
33 4930 23 7 0 0
34 6750 31 7 0 0
35 1241 6 2 0 0
36 1241 6 2 0 0
37 3571 29 2 0 0
38 0 0 0 0 0
39 1010 5 1 0 0
40 1010 5 1 0 0
41 88859 72 3 0 1
42 90783 81 4 0 1
43 2914 19 3 0 0
44 0 0 0 0 0
45 2157 17 1 0 0
46 2157 17 1 0 0
47 78 1 1 0 0
.

时间(第一列)应该是子词典的关键。

所以这背后的想法是我以后可以在给定的时间x,以及时间y处的BLOCK数量和时间z处的SESSION值,以及等等来访问PKT值等等。

提前致谢

1 个答案:

答案 0 :(得分:1)

您可能不希望使用字典,而是需要包含所有数据条目字典的数组。在Objective-C中解析类似内容的最简单方法是在NSString中使用componentsSeparatedByString方法

NSString* dataString = <Your Data String> // Assumes the items are separated by newlines

NSArray* items = [dataString componentsSeparatedByString:@"\n"];

NSMutableArray* dataDictionaries = [NSMutableArray array];

for (NSString* item in items) {
    NSArray* elements = [item componentsSeparatedByString:@" "];
    NSDictionary* entry = @{
        @"time":    [elements objectAtIndex:0], 
        @"bytes":   [elements objectAtIndex:1],
        @"pkt":     [elements objectAtIndex:2],
        @"block":   [elements objectAtIndex:3],             @"drop":    [elements objectAtIndex:4],
        @"session": [elements objectAtIndex:5],
    };

    [dataDictionaries addObject: entry];
}
相关问题