如何使用 NSNumber 而不是 Objective-C 中的 NSString 访问 NSDictionary 中的键对象

How to access Object of Key in NSDictionary with NSNumber instead of NSString in Objective-C

我有一个 NSDictionaryInt 变量:

mainDic = @{@1:@"1.jpg",@2:@"2.jpg"};
indexpath.row = 2;

我想使用 indexpath.row 访问值 2 的对象,如下所示:

cell.pic.image = [UIImage imageNamed:mainDic[indexpath.row]];

但是没用。 ...

你的钥匙应该在左边,而不是在右边。还有一个错字,我认为:@"2,jpg"。但应该是@"2.jpg"。 但通常为此使用数组而不是 NSDictionary。因为我记得 Integer 不能作为键。

检查您的输入字典。您可能输入了错误的图像名称。将其替换为:

mainDic = @{@"1" : @"1.jpg", @"2" :@"2.jpg"};
cell.pic.image = [UIImage imageNamed:[mainDic valueForKey:[NSString stringWithFormat:@"%@", indexpath.row]]];

mainDic = @{@1:@"1.jpg",@2:@"2.jpg"}; 使用 NSNumber 作为字典中的键。

@1 创建了一个 NSNumber,它只是 [NSNumber numberWithInt:1] 的快捷方式。 所以你的字典看起来像这样:NSDictionary <NSNumber *, NSString *> *mainDic;.

NSIndexPath 的第 属性 行是一个只读整数。 您尝试使用整数而不是 NSNumber 作为键来访问您的 NSDictionary,正确的调用应该是:

NSNumber *row = [NSNumber numberWithInteger:indexpath.row];
cell.pic.image = [UIImage imageNamed:mainDic[row]];

但我只想使用一个数组,从中访问图像的方式更简单。

NSArray *images = @[@"1.jpg",
                    @"2.jpg",
                    @"3.jpg"];
cell.pic.image = [UIImage imageNamed:images[indexpath.row]];