0

SQLite 데이터베이스로 채워진 UITableView가 있습니다. sectionIndexTitlesForTableView 대리자 메서드를 사용하여 섹션 기반 그룹화를 추가했는데 이제 셀을 선택하면 indexPath.row의 문자열이 선택한 셀의 텍스트와 다릅니다.indexPath.row didSelectRowAtIndexPath에서 임의의 셀 TextLabel을 반환합니다.

내 코드는 다음과 같이 작동합니다.

  1. SQLite 데이터베이스에서 비즈니스를 보유하는 Array를 만듭니다.
  2. 알파벳순으로 정렬합니다.
  3. 데이터베이스의 비즈니스가 시작하는 알파벳 문자 만 사용하여 알파벳 문자 배열을 만듭니다.
  4. NSPredicate와 함께 해당 배열을 사용하여 알파벳순으로 첫 번째 문자로 비즈니스를 그룹화하는 그룹화 된 헤더보기를 제공합니다.
  5. 선택된 행이 NSUserDefaults 파일에 기록되고보기 컨트롤러가 푸시 (iPhone)되거나 해당 키에 옵저버가 추가됩니다 (iPad).

불행히도 헤더보기를 추가 한 이후 indexPath.row는 선택한 Cell의 TextLabel과 완전히 다른 문자열을 반환하므로 다른 비즈니스 정보가 표시됩니다.

다음은 주요 배열 코드의 중요한 블록입니다.

- (void)viewDidLoad 
{ 
// Lots of code... 
arrayName = [[NSMutableArray alloc] init]; 
NameSet = [[NSMutableSet alloc] init]; 
sortedArray = [arrayName sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)]; 

alphabet = [[NSMutableArray alloc] init]; 
[alphabet addObject:@"{search}"]; 
for (int i=0; i<[sortedArray count]-1; i++) 
{ 
    char alphabetUni = [[sortedArray objectAtIndex:i] characterAtIndex:0]; 
    NSString *uniChar = [NSString stringwithFormat:@"%c", alphabetUni]; 
    if (![alphabet containsObject:uniChar]) 
    { 
    [alphabet addObject:uniChar]; 
    } 
} 
} 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return [alphabet count]; 
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
NSInteger rows = 0; 

NSString *alpha = [alphabet objectAtIndex:section]; 

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alpha]; 
businesses = [sortedArray filteredArrayUsingPredicate:predicate]; 

if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){ 
    rows = [self.searchResults count]; 
} 
else { 
    rows = [businesses count]; 
} 

    return rows; 
} 

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection (NSInteger)section 
{ 
    return [alphabet objectAtIndex:section]; 
} 

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    NSString *CellIdentifier = @"Cell"; 
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
    cell = [[UITableViewCell alloc] 
      initWithStyle:UITableViewCellStyleDefault 
      reuseIdentifier:CellIdentifier]; 

    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator; 
    } 

    NSString *alpha = [alphabet objectAtIndex:indexPath.section]; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alpha]; 
    businesses = [sortedArray filteredArrayUsingPredicate:predicate]; 

    if ([tableView isEqual:self.searchDisplayController.searchResultsTableView]){ 
    cell.textLabel.text = 
    [self.searchResults objectAtIndex:indexPath.row]; 
    } 
    else{ 
     NSString *cellValue = [businesses objectAtIndex:indexPath.row]; 
     cell.textLabel.text = cellValue; 
    } 
    return cell; 

    } 

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
NSString *selected = nil; 

if (tableView == self.tableView) 
{ 
    selected = [businesses objectAtIndex:indexPath.row]; 
} 
else if (tableView == searchDis.searchResultsTableView) 
{ 
    selected = [filteredData objectAtIndex:indexPath.row]; 
} 

[def setObject:selected forKey:@"NameChoiceDetail"]; 

if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) 
{ 
    [self performSegueWithIdentifier:@"NameDetailPush" sender:self]; 

} 
} 

// 내 끔찍한 서면 코드를 실례합니다. 나는 Objective-C를 4 개월 동안, 그리고 프로그래밍을 약 8 개월 동안 만 해왔다. 모든 제안/최적화가 정식으로 언급 될 것입니다.

+0

정말 무작위입니까? 문자열로 다우 버릴 수있는 모든 단계에서 NSLog를 추가하십시오. didSelectRowAtIndexPath에서 indexPath = [businesses objectAtIndex : indexPath.row]를 수행하고 있지만 cellForRow에서 NSString * cellValue = [enterprises objectAtIndex : indexPath.row]를 잘못하고있는 것 같습니다. 섹션이 확인되지 않습니다. if (indexPath.section = someValue) 그런 다음 특정 작업을 수행하십시오. indexPath.row 값은 테이블 뷰의 각 섹션에 대해 0부터 시작합니다. –

+0

indexPath 값의 어설 션이 왜 거기에 설정되었는지 알 수 없습니다. 나는 그것을 고치려고 생각하고 있었다. 현재 (현재 작동중인) 코드에는 없으므로 안심하고 나머지는 편집했습니다. – Giz

답변

0

테이블보기는 섹션을 사용하지만 구현시 tableView:didSelectRowAtIndexPath:은 인덱스 경로의 섹션을 평가하지 않습니다. 그래서 코드에는 뭔가 빠져 있습니다.

또한 businesses 변수 (인스턴스 변수 일 수도 있음)를 사용하는 것이 매우 이상하다는 것을 알았습니다. tableView:cellForRowAtIndexPath:의 값이 할당되지만 사용되는 경우에도 tableView:didSelectRowAtIndexPath:에는 할당되지 않습니다. 따라서 결과가 마지막으로 표시되는 표 셀에 따라 결과가 달라지면 결과는 사용자 상호 작용 스크롤에 따라 달라집니다. 이것이 성과가 무작위로 보이는 이유 일 수 있습니다.

+0

감사합니다 a gazillion !!! didSelectRowAtIndexPath 메서드에서 "business"(NSMutableArray) 값을 다시 초기화하면 이제 내 선택 항목이 올바르게 인식됩니다. – Giz