将词典转换为一个数组

时间:2012-08-17 07:20:26

标签: iphone objective-c ios cocoa-touch foundation

此代码:

for (NSDictionary *object in JSONArray) {
         NSMutableArray *birdtemp = [[NSMutableArray alloc] initWithObjects:object[@"case_name"], nil];
        [allparts addObject:birdtemp];
    }

输出此日志:

log: (
        (
        "NZXT Phantom 410"
    ),
        (
        "Thermaltake MK+"
    )
)

我想知道我可以用什么代码将日志记录到一个数组中,如:

log: (

    "NZXT Phantom 410",
    "Thermaltake MK+"
)

Json Array是:

log: (
        {
        "case_color" = White;
        "case_description" = "";
        "case_image" = "http://sitecom/get/parts/part_images/nzxtphantom410.jpeg";
        "case_name" = "NZXT Phantom 410";
        "case_price" = "99.99";
        "case_type" = ATX;
        id = 1;
    },
        {
        "case_color" = Black;
        "case_description" = "";
        "case_image" = "http://site.com/get/parts/part_images/thernaltake-mkplus.jpeg";
        "case_name" = "Thermaltake MK+";
        "case_price" = "84.99";
        "case_type" = ATX;
        id = 2;
    }
)

4 个答案:

答案 0 :(得分:1)

排除故障并得到了这个:

allparts = [[NSMutableArray alloc] init];
    NSString *birdtemp;
    for (NSDictionary *object in JSONArray) {
            birdtemp = object[@"case_name"];
        [allparts addObject:birdtemp];
    }

答案 1 :(得分:1)

获得所需结果的一种简单方法是使用键值编码(KVC):

NSArray *allparts = [JSONArray valueForKey:@"case_name"];

以这种方式在数组上使用的键值编码起初可能看起来有点反直觉,但它非常强大。

答案 2 :(得分:1)

   NSMutableArray *array = [[NSMutableArray alloc] init];
    for (NSDictionary *dict in JSONArray) {

        [array addObject:[dict objectForKey:@"case_name"]];
    }
    NSLog(@"Your Array: %@",array);

我认为这会对你有所帮助。

答案 3 :(得分:0)

NSMutableArray *birdtemp  = [NSMutableArray ....];   
     for (NSDictionary *object in JSONArray) {
               [birdtemp addObject:object[@"case_name"]];
      }
     [allparts addObject:birdtemp];