2015-02-23 74 views
0

我有UITableView和NSDictionary。它填充像如下: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是專輯類的類,返回的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]}; 
} 

這就是我從教程採取代碼,因此,在下面的行我們填充的tableView數據與NSDictionary的值:

-(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值,而不是一個整數。

回答

1

這是寫代碼只是一小段路:

currentAlbumData[@"titles"][indexPath.row]是一樣[[currentAlbumData objectForKey:@"titles"] objectAtIndex:indexPath.row]。在這裏,currentAlbumData是一本字典。你得到它的關鍵titles,這是(據說)一個數組。然後你得到這個數組的索引indexPath.row的對象。

+1

ü意味着NSDictionary包含一個數組(或幾個)?對於NSArray而言,像通過索引獲取值的行爲當然是可以接受的:) – 2015-02-23 07:16:14

+0

稍後我會添加詳細的描述。 – n00bProgrammer 2015-02-23 09:23:21

1

titles是NSStrings的NSArray的關鍵。 values也是如此。

currentAlbumData[@"titles"]向字典詢問titles關鍵路徑處的值。這將返回由NSUIntegers索引的NSArray,如indexPath.row。

1

標題是一個數組如果你發現一個數組內這混亂的,然後更好地存儲標題所以要得到在特定的索引值,你可以使用

cell.textlabel.text = [[currentAlbumData valueForKey:@"titles"] objectAtIndex:indexPath.row]; 

,然後用它下面

NSArray *titles = [currentAlbumData valueForKey:@"titles"]; 
cell.textlabel.text = [titles objectAtIndex:indexPath.row];