2013-04-29 1 views
0
dictionaryOfWebsites = [[NSMutableDictionary alloc] init]; 
[dictionaryOfWebsites setObject:@"http://www.site1.com" forKey:@"Site1"]; 
[dictionaryOfWebsites setObject:@"http://www.site2.com" forKey:@"Site2"]; 
[dictionaryOfWebsites setObject:@"http://www.site3.com" forKey:@"Site3"]; 
[dictionaryOfWebsites setObject:@"http://www.site4.com" forKey:@"Site4"]; 

위의 내용은 내 사전입니다. UITableViewCell의 텍스트에 "Site1"이 표시되고 하위 텍스트에 URL이있는 테이블 뷰가 필요합니다. 내 NSMutableDictionary에서 UITableView로 데이터를로드하는 방법

내가이

NSArray *keys = [dictionaryOfWebsites allKeys]; 

// values in foreach loop 
for (NSString *key in keys) { 
    NSLog(@"%@ is %@",key, [dict objectForKey:key]); 
} 

내 접근이 최고 아닌 경우 도움을 크게

을 감상 할 수있어 나에게 모든 열쇠를 얻을 것이다 알고, 나를 이렇게 내가 배울 수 알려 주시기 바랍니다 당신의 추천.

답변

3

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return [[dictionaryOfWebsites allKeys] count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //Initialize cell of style subtitle 
    NSArray *keys = [[dictionaryOfWebsites allKeys]sortedArrayUsingSelector:@selector(compare:)]; 
    NSString *key = keys[indexPath.row]; 

    cell.textLabel.text = key; 
    cell.detailTextLabel.text = dictionaryOfWebsites[key]; 

    return cell; 
} 

편집을보십시오 : 표현의 이러한 종류의 사전의 배열을 가지고하는 것이 좋습니다.

두 개의 키 값 쌍 Title 및 Subtitle이있는 각 사전.

self.dataArray = [NSMutableArray array]; 
NSDictionary *dict = @{@"Title":@"Site1",@"Subtitle":@"http://www.site1.com"}; 
[dataArray addObject:dict]; 
//Add rest of the dictionaries to the dataArray 


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    // Return the number of rows in the section. 
    return [self.dataArray count]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    //Initialize cell of style subtitle 

    NSDictionary *dict = self.dataArray[indexPath.row]; 
    cell.textLabel.text = dict[@"Title"]; 
    cell.detailTextLabel.text = dict[@"Subtitle"]; 

    return cell; 
} 
+0

'- [NSDictionary allKeys]'를 사용하는 것은 좋은 방법이 아닙니다. 왜냐하면 키의 순서가 여러 호출에서 동일하게 유지된다는 보장이 없기 때문입니다. 문서에서 :'배열 요소의 순서는 정의되지 않았습니다. ' – Mar0ux

+0

@ Mar0ux 정확히, 나는 이것을 제거하기위한 또 다른 제안을했다. 키의 본질이 알려진 경우이를 제거하기 위해 정렬을 수행 할 수 있습니다. – Anupdas

+0

확인. 첫 번째 솔루션을 제거하거나 사람들이 직접 코드를 복사하지 않도록 정렬을 포함하도록 수정하는 것이 좋습니다. – Mar0ux

0

당신은 시도 할 수 있습니다 :이 경우

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
//cell initialization code 
NSString *title = [keys objectAtIndex:indexPath.row]; 
cell.textLabel.text = title; 
cell.detailTextLabel.text = [dictionaryOfWebsites objectForKey:title]; 

return cell; 
} 

는 속성으로 키 배열을 선언합니다.

관련 문제