DirTy™의 하루일과/DirTy™의 가당찮은iOS

[IOS] NSArray에 NSDictionary데이터 넣기

DirTy™ 2015. 2. 5. 19:18

NSArray에 하나의 데이터가 아닌 여러개의 또 뭔가 구분을 지어서 데이터를 넣고 싶은경우가

종종 생기는데 이게 초심자에게는 골치아픈 문제다. 나또한 그러했다.

아래와 같은 방법으로 처리하면 아주쉽다.

아래의 코드로 테이블뷰에서 섹션헤더, 섹션푸터, 테이블뷰 셀에 들어갈 텍스트를 넣어서 표현이 가능하다.


   NSArray *myList = [[NSArray alloc] init];


    [myList addObject:

     [NSDictionary dictionaryWithObjectsAndKeys:

      @"헤더타이틀1", @"grouptitle",

      //@"푸터타이틀1", @"endtitle",

      [NSMutableArray arrayWithObjects:

       [NSDictionary dictionaryWithObjectsAndKeys:@"셀텍스트", @"text", nil],

       nil],@"data",

      nil]

     ];


    [myList addObject:

     [NSDictionary dictionaryWithObjectsAndKeys:

      @"헤더타이틀"@"grouptitle",

      //@"푸터타이틀", @"endtitle",

      [NSMutableArray arrayWithObjects:

       [NSDictionary dictionaryWithObjectsAndKeys:@"셀텍스트", @"text"nil],

       nil],@"data",

      nil]

     ];


아래와 같이 섹션 카운트를 쉽게 가져올수 있다. 위에서 데이터를 2개 add했으니 2가 반환될것이다.

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section

{

    // Return the number of rows in the section.

    return [[[myList objectAtIndex:section] objectForKey:@"data"] count];

}


섹션에 대한 헤더타이틀을 쉽게 넣을수 있다.

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {

    return [[myList objectAtIndex:section] objectForKey:@"grouptitle"];

}


마찬가지로 섹션에 대한 푸터타이틀을 쉽게 넣을수 있다.

- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section

{

    return [[myList objectAtIndex:section] objectForKey:@"endtitle"];

}


셀텍스트에 들어갈 문자열은 아래와같이 가져온다.

[[[[myList objectAtIndex:indexPath.section] objectForKey:@"data"] objectAtIndex:indexPath.row] objectForKey:@"text"];


의외로 상당히 유용하니 잊어먹지 않도록 기록해 놓는다.