2010-05-09 17 views
1

J'ai suivi un tutoriel pour implémenter une barre de recherche.Pousser différentes vues d'une table

Cependant, je n'arrive pas à pousser différentes vues. Voici à quoi ressemble mon didsSelectRowAtIndexPath.

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

if(searching) 
    selectedCountry = [copyListOfItems objectAtIndex:indexPath.row]; 
else { 

    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; 
    NSArray *array = [dictionary objectForKey:@"Countries"]; 
    selectedCountry = [array objectAtIndex:indexPath.row]; 
} 

//Initialize the detail view controller and display it. 
if ([[listOfItems objectAtIndex:indexPath.row] isEqual:@"neon"]){ 
Neon *abo = [[Neon alloc] initWithNibName:@"Neon" bundle:nil]; 
//dvController.selectedCountry = selectedCountry; 
[self.navigationController pushViewController:abo animated:YES]; 
[abo release]; 
} 

} 

Et voici le message debuger lorsque je clique sur le néon: 2010-05-09 08: 47: 27,516 iTeachU [3821: 307] * Mettre fin à l'application du fait exception uncaught 'NSRangeException', raison: '* - [NSMutableArray objectAtIndex:]: index 60 au-delà des limites [0 .. 0]' *** Pile d'appel au premier lancement: terminate appelée après avoir lancé une instance de 'NSException' Signal reçu du programme: "SIGABRT" .

Si quelqu'un a un moyen de pousser des vues basées sur le texte des cellules, il serait grandement apprécié. Merci

Modifier Tout .m

- (void)viewDidLoad { 
[super viewDidLoad]; 
listOfItems = [[NSMutableArray alloc] init]; 

NSArray *ElementsArray = [NSArray arrayWithObjects:@"Actinium", 
          @"Aluminium", 
          @"Americium", 
          @"Antimony", 
          @"Argon", 
          @"Arsenic", 
          @"Astatine", 
          @"Barium", 
          @"Berkelium", 
          @"Beryllium", 
          @"Bismuth", 
          @"Bohrium", 
          @"Boron", 
          @"Bromine", 
          @"Cadmium", 
          @"Cesium", 
          @"Calcium", 
          @"Californium", 
          @"Carbon", 
          @"Cerium", 
          @"Chlorine", 
          @"Chromium", 
          @"Cobalt", 
          @"Copper", 
          @"Curium", 
          @"Darmstadtium", 
          @"Dubnium", 
          @"Dysprosium", 
          @"Einsteinium", 
          @"Erbium", 
          @"Europium", 
          @"Fermium", 
          @"Fluorine", 
          @"Francium", 
          @"Gadolinium", 
          @"Gallium", 
          @"Germanium", 
          @"Gold", 
          @"Hafnium", 
          @"Hassium", 
          @"Helium", 
          @"Holmium", 
          @"Hydrogen", 
          @"Indium", 
          @"Iodine", 
          @"Iridium", 
          @"Iron", 
          @"Krypton", 
          @"Lanthanum", 
          @"Lawrencium", 
          @"Lead", 
          @"Lithium", 
          @"Lutetium", 
          @"Magnesium", 
          @"Manganese", 
          @"Meitnerium", 
          @"Mendelevium", 
          @"Mercury", 
          @"Molybdenum", 
          @"Neodymium", 
          @"neon", 
          @"Neptunium", 
          @"Nickel", 
          @"Niobium", 
          @"Nitrogen", 
          @"Nobelium", 
          @"Osmium", 
          @"Oxygen", 
          @"Palladium", 
          @"Phosphorus", 
          @"Platinum", 
          @"Plutonium", 
          @"Polonium", 
          @"Potassium ", 
          @"Praseodymium", 
          @"Promethium", 
          @"Protactinium", 
          @"Radium", 
          @"Radon", 
          @"Rhenium", 
          @"Rhodium", 
          @"Roentgenium", 
          @"Rubidium", 
          @"Ruthenium", 
          @"Rutherfordium", 
          @"Samarium", 
          @"Scandium", 
          @"Seaborgium", 
          @"Selenium", 
          @"Silicon", 
          @"Silver", 
          @"Sodium", 
          @"Strontium", 
          @"Sulfur", 
          @"Tantalum", 
          @"Technetium", 
          @"Tellurium", 
          @"Terbium", 
          @"Thallium", 
          @"Thorium", 
          @"Thulium", 
          @"Tin", 
          @"Titanium", 
          @"Tungsten", 
          @"Ununbium", 
          @"Ununhexium", 
          @"Ununoctium", 
          @"Ununpentium", 
          @"Ununquadium", 
          @"Ununseptium", 
          @"Ununtrium", 
          @"Uranium", 
          @"Vanadium", 
          @"Xenon", 
          @"Ytterbium", 
          @"Yttrium", 
          @"Zinc", 
          @"Zirconium", nil]; 
NSDictionary *ElementsDict = [NSDictionary dictionaryWithObject:ElementsArray  forKey:@"Elements"]; 


[listOfItems addObject:ElementsDict]; 

//Initialize the copy array. 
copyListOfItems = [[NSMutableArray alloc] init]; 

//Set the title 
self.navigationItem.title = @"Elements"; 

//Add the search bar 
self.tableView.tableHeaderView = searchBar; 
searchBar.autocorrectionType = UITextAutocorrectionTypeNo; 

searching = NO; 
letUserSelectRow = YES; 
} 

-(IBAction) back:(id)sender{ 
[self.navigationController popViewControllerAnimated:NO]; 
} 
// Override to allow orientations other than the default portrait orientation. 
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { 
// Return YES for supported orientations 
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); 
} 



#pragma mark - 
#pragma mark Table view data source 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 

if (searching) 
    return 1; 
else 
    return [listOfItems count]; 
} 



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

if (searching) 
    return [copyListOfItems count]; 
else { 

    //Number of rows it should expect should be based on the section 
    NSDictionary *dictionary = [listOfItems objectAtIndex:section]; 
    NSArray *array = [dictionary objectForKey:@"Elements"]; 
    return [array count]; 
} 
} 
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { 

if(searching) 
    return @"Search Results"; 

if(section == 0) 
    return @"Elements"; 
} 

// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

static NSString *CellIdentifier = @"Cell"; 

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
if (cell == nil) { 
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; 
} 

// Configure the cell... 

if(searching) 
    cell.text = [copyListOfItems objectAtIndex:indexPath.row]; 
else { 

    //First get the dictionary object 
    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; 
    NSArray *array = [dictionary objectForKey:@"Elements"]; 
    NSString *cellValue = [array objectAtIndex:indexPath.row]; 
    cell.text = cellValue; 
} 

return cell; 
} 

- (NSIndexPath *)tableView :(UITableView *)theTableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

if(letUserSelectRow) 
    return indexPath; 
else 
    return nil; 
} 


- (void) searchBarTextDidBeginEditing:(UISearchBar *)theSearchBar { 

//This method is called again when the user clicks back from teh detail view. 
//So the overlay is displayed on the results, which is something we do not want to happen. 
if(searching) 
    return; 

//Add the overlay view. 
if(ovController == nil) 
    ovController = [[OverlayViewController alloc] initWithNibName:@"OverlayView" bundle:[NSBundle mainBundle]]; 

CGFloat yaxis = self.navigationController.navigationBar.frame.size.height; 
CGFloat width = self.view.frame.size.width; 
CGFloat height = self.view.frame.size.height; 

//Parameters x = origion on x-axis, y = origon on y-axis. 
CGRect frame = CGRectMake(0, yaxis, width, height); 
ovController.view.frame = frame;  
ovController.view.backgroundColor = [UIColor grayColor]; 
ovController.view.alpha = 0.5; 

ovController.rvController = self; 

[self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view]; 

searching = YES; 
letUserSelectRow = NO; 
self.tableView.scrollEnabled = NO; 

//Add the done button. 
self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] 
              initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
              target:self action:@selector(doneSearching_Clicked:)] autorelease]; 
} 

- (void)searchBar:(UISearchBar *)theSearchBar textDidChange:(NSString *)searchText { 

//Remove all objects first. 
[copyListOfItems removeAllObjects]; 

if([searchText length] > 0) { 

    [ovController.view removeFromSuperview]; 
    searching = YES; 
    letUserSelectRow = YES; 
    self.tableView.scrollEnabled = YES; 
    [self searchTableView]; 
} 
else { 

    [self.tableView insertSubview:ovController.view aboveSubview:self.parentViewController.view]; 

    searching = NO; 
    letUserSelectRow = NO; 
    self.tableView.scrollEnabled = NO; 
} 

[self.tableView reloadData]; 
} 

- (void) searchBarSearchButtonClicked:(UISearchBar *)theSearchBar { 

[self searchTableView]; 
} 

- (void) searchTableView { 

NSString *searchText = searchBar.text; 
NSMutableArray *searchArray = [[NSMutableArray alloc] init]; 

for (NSDictionary *dictionary in listOfItems) 
{ 
    NSArray *array = [dictionary objectForKey:@"Elements"]; 
    [searchArray addObjectsFromArray:array]; 
} 

for (NSString *sTemp in searchArray) 
{ 
    NSRange titleResultsRange = [sTemp rangeOfString:searchText options:NSCaseInsensitiveSearch]; 

    if (titleResultsRange.length > 0) 
     [copyListOfItems addObject:sTemp]; 
} 

[searchArray release]; 
searchArray = nil; 
} 

- (void) doneSearching_Clicked:(id)sender { 

searchBar.text = @""; 
[searchBar resignFirstResponder]; 

letUserSelectRow = YES; 
searching = NO; 
self.navigationItem.rightBarButtonItem = nil; 
self.tableView.scrollEnabled = YES; 

[ovController.view removeFromSuperview]; 
[ovController release]; 
ovController = nil; 

[self.tableView reloadData]; 
} 

// Remplacer pour soutenir la modification de la vue de la table. - (void) tableView: (UITableView *) tableView commitEditingStyle: (UITableViewCellEditingStyle) editingStyle forRowAtIndexPath: (NSIndexPath *) indexPath {

if (editingStyle == UITableViewCellEditingStyleDelete) { 
    // Delete the row from the data source 
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; 
} 
else if (editingStyle == UITableViewCellEditingStyleInsert) { 
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view 
} 

} */

#pragma mark - 
#pragma mark Table view delegate 

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

if(searching) 
    selectedCountry = [copyListOfItems objectAtIndex:indexPath.row]; 
else { 

    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; 
    NSArray *array = [dictionary objectForKey:@"Countries"]; 
    selectedCountry = [array objectAtIndex:indexPath.row]; 
} 

//Initialize the detail view controller and display it. 
if ([[listOfItems objectAtIndex:indexPath.row] isEqual:@"neon"]){ 
Neon *abo = [[Neon alloc] initWithNibName:@"Neon" bundle:nil]; 
//dvController.selectedCountry = selectedCountry; 
[self.navigationController pushViewController:abo animated:YES]; 
[abo release]; 
} 

} 


#pragma mark - 
#pragma mark Memory management 

- (void)didReceiveMemoryWarning { 
// Releases the view if it doesn't have a superview. 
[super didReceiveMemoryWarning]; 

// Relinquish ownership any cached data, images, etc that aren't in use. 
} 

- (void)viewDidUnload { 
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. 
// For example: self.myOutlet = nil; 
} 


- (void)dealloc { 
[back release]; 
[tableView release]; 
[super dealloc]; 
} 


@end 

Répondre

0

Selon les exceptions, vous appelez objectAtIndex: avec une valeur de 60 et le NSMutableArray ne contient aucun élément (plage 0..0). Vous devez résoudre ce problème avant d'accéder au code push. Vous devriez être capable de dire à partir de la pile d'appels dans le débogueur quel tableau est accessible lorsque l'exception se produit ou vous pouvez ajouter NSLog avant de faire objectAtIndex: pour voir ce que vous avez.Par exemple, vous avez:

if ([[listOfItems objectAtIndex:indexPath.row] isEqual:@"neon"]){ 

Si vous ajoutez cette ligne suivante avant celle ci-dessus, vous seriez en mesure de voir ce que l'index que vous essayez d'accéder (indexPath.row) et combien vous avez réellement dans LISTOFITEMS :

NSLog(@"listOfItems has %d, accessing %d", [listOfItems count], indexPath.row); 
+0

Merci pour votre réponse. J'ai cliqué sur le 3ème élément et j'ai obtenu ceci: 2010-05-09 19: 43: 49.392 iTeachU [4674: 307] listOfItems a 1, en accédant 3 Existe-t-il un moyen de dire ceci pour pousser une vue en utilisant la rangée 3 ou quelque chose comme cette? – Tanner

+0

Vous posez la mauvaise question. Vous devriez demander pourquoi y a-t-il seulement 1 élément dans listOfItems? Comment pouvez-vous espérer obtenir l'article 3 quand il n'y en a qu'un? – progrmr

0

Ne sachant pas beaucoup sur votre code , Je ne peux pas vous dire le problème exact, cependant:

En haut, vous différenciez entre deux tableaux différents en fonction de la valeur de searching. Plus tard, vous n'utilisez que le tableau que vous utiliseriez lorsque searching est faux, avec le même index, qui semble être un tableau de NSDictionary s, et non NSString s. Vous semblez également y accéder en utilisant indexPath.section la première fois, et indexPath.row la deuxième fois.

La ligne dont je parle, en particulier, est celui-ci:

if ([[listOfItems objectAtIndex:indexPath.row] isEqual:@"neon"]){ 

Basé sur le code précédent, qui est, cette ligne:

NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; 

Je devine que listOfItems contient un nombre d'éléments égal au nombre de sections dans votre vue de table, pas le nombre de lignes dans la section sur laquelle vous avez cliqué, et je devine également que la valeur de retour ne sera jamais égale à @"neon" car il s'agit d'un NSDictionary .

+0

Ive a ajouté le reste de la classe comme une modification. Je ne peux toujours pas avoir une vue à pousser. Avec le code fourni pouvez-vous voir quelque chose qui obtiendrait une nouvelle vue? – Tanner

+0

D'où voulez-vous que ce tableau "Pays" provienne si la seule entrée utilise la clé "Elements"? –

+0

Son été changé en éléments. Aucun changement dans la sélection ou la poussée n'a eu lieu. – Tanner

0

Résolu avec ce code pour quiconque se demandant. - (void) tableView: (UITableView *) tableView didSelectRowAtIndexPath: (NSIndexPath *) indexPath { NSString * selectedCountry = nil;

if(searching) 
    selectedCountry = [copyListOfItems objectAtIndex:indexPath.row]; 
else { 

    NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; 
    NSArray *array = [dictionary objectForKey:@"Elements"]; 
    selectedCountry = [array objectAtIndex:indexPath.row]; 
} 

//Initialize the detail view controller and display it. 
NSLog(@"listOfItems has %d, accessing %d", [listOfItems count], indexPath.row); 
NSDictionary *dictionary = [listOfItems objectAtIndex:indexPath.section]; 
NSArray *array = [dictionary objectForKey:@"Elements"]; 
NSString *cellValue = [array objectAtIndex:indexPath.row]; 

if ([cellValue isEqual:@"neon"]){ 
    NSLog(@"Neon"); 
    Neon *abo = [[Neon alloc] initWithNibName:@"Neon" bundle:nil]; 
    [self.navigationController pushViewController:abo animated:YES]; 
    NSLog(@"Neon Worked"); 
    [abo release]; 
} 

}

+0

Si l'une de ces réponses permettait de résoudre votre problème ou de vous guider dans la bonne direction, il serait bon d'en choisir un ou un vote positif s'il vous était utile. – progrmr

+0

Le problème a été résolu dans le sens où il a poussé cette vue. Cependant, la barre de recherche utilise une copie des vues. Je peux obtenir les copyListItems et les listItems pour pousser seulement une vue simple. Sélectionner d'autres force l'application à se bloquer. J'ai toujours besoin d'un moyen de pousser toutes les vues. – Tanner

+0

En déclarant une chaîne et le paramètre isEqual fonctionne pour tous y compris la recherche. Votre code de nslog a aidé. Je vais le marquer comme la réponse car elle m'a conduit sur le bon chemin. Merci de votre aide. – Tanner