使用NSArray KeyValue问题调用NSDictionary

时间:2013-12-03 09:44:16

标签: ios objective-c nsarray nsdictionary

我有一个加载了其他方法数据的数组。数据类型与代码中KEYS的调试类似。

<__NSArrayI 0x9e82fc0>( { "choice_name" = "Data0"; }, { "choice_name" = "Data1"; }, { "choice_name" = "Data2"; },

然后我用不同的方法调用它两次,如下面的评论,我得到了arrray的值:array0array1 nil。我的问题在哪里?

- (void)requestPosistion:(ASIFormDataRequest *)request{

NSData *responseData = [request responseData];
NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];

NSDictionary *result = [jsonString JSONValue];
[jsonString release];

if (![SettingVO isValidResponce:result]) return;

CXMLDocument *doc = [[[CXMLDocument alloc] initWithXMLString:[result objectForKey:@"Response"] options:0 error:nil] autorelease];

NSArray *nodes = [doc nodesForXPath:@"/root" error:nil];

NSLog(@"choiceList is %@", nodes);

if([[[[nodes objectAtIndex:0] attributeForName:@"success"] stringValue] isEqualToString:@"true"])
{

    NSArray *nodes3 = NULL;

    nodes3 = [doc nodesForXPath:@"/root/cl_choicelist/cl_choice" error:nil];

    NSLog(@"node3%@", nodes3);

    res = [[NSMutableArray alloc] init];

    for (CXMLElement *node in nodes3) {
        item = [[NSMutableDictionary alloc] init];

        int counter;
        for(counter = 0; counter < [node childCount]; counter++) {
            [item setObject:[[node childAtIndex:counter] stringValue] forKey:[[node childAtIndex:counter] name]];
        }

        [item setObject:[[node attributeForName:@"choice_name"] stringValue] forKey:@"choice_name"];

        NSLog(@"item %@", item);
        [res addObject:item];
        [item release];
    }

    NSLog(@"res %@", res);
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *plistDict = [[NSDictionary alloc] initWithObjects:res forKeys:res];

    //NSArray *keys = [plistDict allKeys];

    //NSArray *array0 = [[NSArray alloc] initWithArray:[plistDict valueForKey:@"choice_name"]]; //array0 = nil.
    NSArray *array1 = [plistDict objectForKey:@"choice_name"]; //array1 = nil.

4 个答案:

答案 0 :(得分:0)

<__NSArrayI 0x9e82fc0>( { "choice_name" = "Data0"; }, { "choice_name" = "Data1"; }, { "choice_name" = "Data2"; },

这是一个数组。在数组中,您有NSDictionary的对象,其键为“choice_name”。

因此,为了检索,您需要遍历数组以获取所有kvp。

答案 1 :(得分:0)

工作代码如下:

 [[res objectAtIndex:0] objectForKey:@"choice_name"] //returns Data0
 [[res objectAtIndex:1] objectForKey:@"choice_name"] //returns Data1

最有可能你想在objectAtIndex上使用“indexPath”:

 [[res objectAtIndex:[indexPath row]] objectForKey:@"choice_name"]

答案 2 :(得分:0)

用以下代码替换你的行:

NSString *str = [plistDict valueForKey:@"choice_name"];

您拥有该键或数组的字符串。 总是很好,以确保你的plistDict不是零。

答案 3 :(得分:0)

在NSDictionary中,您可以使用密钥@choice_name进行一对。即使你在NSDictionary中“放置”多一个,其他所有内容都会覆盖以前的值。

所以valueForKey可以返回一个对象,而不是整个数组,因为有一个键@choice_name