Dictionary对象的问题

时间:2011-11-01 06:04:28

标签: iphone objective-c ios4

我创建了一个按钮动作方法。使用数组中的值初始化NSDictionary并为其分配值。在控制台中打印字典对象时获取正确的值。分配给“NSString * value”时,打印值如Value为:144964992.但是在控制台上获取正确的值,如0,1,2,3 ......

-(IBAction)takeDecision:(id)sender
    {
        NSLog(@"FINAL DECISION");
        NSMutableDictionary *dict =  [[NSMutableDictionary alloc]init];
        for(int i = 0; i < [choices count]; i++)
        {
            //[resultChoice indexOfObject:[NSNumber numberWithInt:i]];

            [dict setObject:[NSNumber numberWithInt:i] forKey:[choices objectAtIndex:i]];   
        }

        for (id key in dict) {

            NSLog(@"key: %@, value: %@", key, [dict objectForKey:key]);

        }




        for(int i = 0; i < [preferences count]; i++)
        {
            for(int j = 0; j < [choices count]; j++)
            {
                //NSLog(@"Number of cells: %d", [[myTable] numberOfRowsInSection:0]); // This writes out "Number of cells: 6"


                UITableViewCell *cell = [myTable cellForRowAtIndexPath:[NSIndexPath indexPathForRow:j inSection:i]];
                if(cell == nil) {
                    NSLog(@"CELL IS NIL");
                }

                NSArray *array = cell.contentView.subviews;
                NSLog(@"NUMBER OF OBJECTS: %d",[array count]);
                UIButton *test = (UIButton *)[array objectAtIndex:1];
                UIImage *newImage = [test currentBackgroundImage];
                NSLog(@"Image is %@",newImage.CGImage);

                NSLog(@"*************TEST VALUE IS:%@",[dict objectForKey:[choices objectAtIndex:j]]);

                NSString *value = [dict objectForKey:[choices objectAtIndex:j]];
                NSLog(@"--------> Value is: %d", value);
                if(newImage == [UIImage imageNamed:@"thumbsup_selected.png"])
                {
                    [dict setValue:[NSNumber numberWithInt: value+1] forKey:[choices objectAtIndex:j]];
                }
                NSLog(@"CELL IS NOT NIL");
            }
        }
        for (id key in dict) {

            NSLog(@"key: %@, value: %@", key, [dict objectForKey:key]);

        }
    }

如果有人可以为它提供解决方案,那将会有所帮助......提前致谢...

3 个答案:

答案 0 :(得分:1)

您尝试使用"%d".%d打印字符串值是为了整数值。正确的格式是

 NSLog(@"--------> Value is: %@", value);

答案 1 :(得分:1)

原因是当您在gdb中打印时,实际上是打印NSNumber的值,这在控制台中看起来是正确的。但你不能直接在NSString中使用NSNumber。所以改变行

 NSString *value = [dict objectForKey:[choices objectAtIndex:j]];

            NSString *value = [NSString stringWithFormat: @"%d",[[dict objectForKey:[choices objectAtIndex:j]] integerValue]];

答案 2 :(得分:0)

您有一个NSNumber对象的字典,但是将这些NSNumber对象中的一个分配给NSString,即使它们是不同类型的对象。打印操作试图将NSNumber打印为NSString,这会产生不可预测的结果。

您可以使用

NSString *value = [[[dict objectForKey:[choices objectAtIndex:j]] stringValue];

将正确的值输入NSString。