NSDictionary语法解释

时间:2015-02-23 06:57:21

标签: ios objective-c

我有UITableView和NSDictionary。它填充如下:

    currentAlbumData = [album tr_tableRepresentation];

专辑是简单的NSObject类:

// h.file
@interface Album : NSObject

@property (nonatomic, copy, readonly) NSString *title, *artist, *genre, *coverUrl, *year;

-(id)initWithTitle:(NSString*)title artist:(NSString*)artist coverUrl:(NSString*)coverUrl year:(NSString*)year;

//m.file

-(id)initWithTitle:(NSString *)title artist:(NSString *)artist coverUrl:(NSString *)coverUrl year:(NSString *)year{

self = [super init];
if (self){

    _title = title;
    _artist = artist;
    _coverUrl = coverUrl;
    _year = year;
    _genre = @"Pop";
}
return self;

};

并且tr_tableRepresentation是Album类的类别,返回NSDictionary:

//h.file

@interface Album (TableRepresentation)

- (NSDictionary*)tr_tableRepresentation;

@implementation专辑(TableRepresentation)

//.m file

- (NSDictionary*)tr_tableRepresentation
{
    return @{@"titles":@[@"Artist", @"Album", @"Genre", @"Year"],
             @"values":@[self.artist, self.title, self.genre, self.year]};
}

这是我从教程中获取的代码,因此,在以下几行中,我们使用NSDictionary值填充tableView数据:

-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];

    //... Cell initialization code

    cell.textLabel.text = currentAlbumData[@"titles"][indexPath.row];
    cell.detailTextLabel.text = currentAlbumData[@"values"][indexPath.row];
}

现在我被卡住了。因为当我看到这样的语法时,我会感到困惑。

cell.textLabel.text = currentAlbumData[@"titles"][indexPath.row];
        cell.detailTextLabel.text = currentAlbumData[@"values"][indexPath.row];

这到底发生了什么?这行代码的作用是什么?我可以理解,我们以某种方式访问​​@"titles"@"values",您能否以更易读的方式重写这些行,而不使用方括号?

我们怎样才能使用indexPath(整数)来获取@"titles"@"values"?这听起来有点傻,但我没理解。我认为我们必须将字符串作为参数来访问NSDictionary值,而不是整数。

3 个答案:

答案 0 :(得分:1)

这只是编写代码的简短方法:

currentAlbumData[@"titles"][indexPath.row][[currentAlbumData objectForKey:@"titles"] objectAtIndex:indexPath.row]相同。这里,currentAlbumData是一本字典。你得到它的关键titles的对象,它是(据说)一个数组。然后你得到这个数组索引indexPath.row的对象。

答案 1 :(得分:1)

titles是NSStrings的NSArray的关键。 values也是如此。

currentAlbumData[@"titles"]向字典询问titles密钥路径的值。这将返回由NSUIntegers索引的NSArray,例如indexPath.row。

答案 2 :(得分:1)

标题是一个数组,因此可以使用

获取特定索引的值
cell.textlabel.text = [[currentAlbumData valueForKey:@"titles"] objectAtIndex:indexPath.row];

如果您发现这个令人困惑,那么最好将标题存储在数组中,然后在

下面使用它
NSArray *titles = [currentAlbumData valueForKey:@"titles"];
cell.textlabel.text = [titles objectAtIndex:indexPath.row];