2013-08-25 45 views
-1

我有一個應用程序,當您使用搜索欄時,根據您放入的內容來過濾患者,但當您單擊某一行時,它總是會在下一個nib文件中顯示相同的數據。我知道這是因爲indexPath是隨着單元格順序的改變而改變的,而它們的數量有沒有辦法讓它走向正確的呢?搜索已過濾的數組索引路徑不正確

IndexPath代碼:

- (void)tableView:(UITableView *)tv didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 
    LSAppDelegate *delegate = (LSAppDelegate *)[[UIApplication sharedApplication] delegate]; 
    PatientController *patient = [[PatientController alloc] initWithIndexPath:indexPath]; 
    [delegate.navController pushViewController:patient animated:YES]; 
    [tv deselectRowAtIndexPath:indexPath animated:YES]; 
} 

搜索代碼:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText { 
    if (searchText.length == 0) { 
     isFiltered = NO; 
    } else { 
     isFiltered = YES; 

     filteredPatients = [[NSMutableArray alloc] init]; 

     for (Patient *patient in patients) { 
      NSRange patientNameRange = [[patient.patientName substringToIndex:1] rangeOfString:searchText options:NSCaseInsensitiveSearch]; 

      if (patientNameRange.location != NSNotFound) { 
       [filteredPatients addObject:[NSString stringWithFormat:@"%@ %@", patient.patientName, patient.patientSurname]]; 
      } 
     } 
    } 
    [self.tableView reloadData]; 
} 
+1

訪問包含導航控制器您的問題有點含糊。您能否詳細說明並顯示一些您正在使用的索引路徑的代碼? –

+0

@XCodeMonkey添加了代碼 – Hive7

回答

3

後你做,你需要刷新UI(想必表視圖)的過濾。現在,行信息應該從過濾結果中獲取 - 這包括行數,單元格內容和單元格選擇源數據。如果在搜索後刷新並使用正確的數據源,則所有內容都將匹配。


不要通過indexPath左右。這是您的表視圖控制器的私有內部狀態(以及如何使用它是基於私有狀態關於搜索是否正在進行)。因此,獲取所選行的患者對象並通過它。例如:

Patient *selectedPatient = nil; 

if (!isFiltered) { 
    selectedPatient = patients[indexPath.row]; 
} else { 
    selectedPatient = filteredPatients[indexPath.row]; 
} 


PatientController *patientController = [[PatientController alloc] initWithIndexPath:indexPath]; 
patientController.patient = selectedPatient; 

這一切都在didSelectRowAtIndexPath:。在PatientController上,您需要從.h文件中刪除indexPath屬性,並將其替換爲patient作爲indexPath的結果得到的patient屬性(或公開公開)。然後,您可以從PatientController中刪除有關indexPath的所有內容,因爲您已經擁有patient實例。

+0

您是否想查看我用於搜索的代碼 – Hive7

+0

PatientController如何使用indexPath? – Wain

+0

它聲明一個像這樣的變量:'NSObject * object = [array objectAtIndex:index.row];'然後像這樣使用對象:'text1.text = object.name;' – Hive7

1

你的錯誤是在你的執行initWithIndexPath,但我不知道你從哪裏沒有發佈它。

您需要使用索引路徑來獲取數據由單元格表示爲,方法是查詢用於填充當前顯示的表的數據結構。所以你想要查詢到filteredPatients,但它的全部只是字符串。填寫真正的患者對象,並在表格詢問細胞時生成字符串。

這是不好的設計,患者視圖控制器應該不知道索引路徑。使用索引路徑讓患者將其傳遞到類似initWithPatient

此外,使用應用程序委託這樣是一個壞主意。您可以使用self.navigationController

+0

我的應用幾乎完成了,所以我現在不想去改變它 – Hive7

+0

下一次。我的要點是,你的bug在init方法中,所以如果你需要更多的幫助,你應該發佈它。 – atomkirk