2012-08-10 49 views
0

我有一個sqlite3數據庫在tableview中加載。我也有一個正常工作的搜索功能。我希望每當我選擇一個單元格時,我將被重定向到視圖控制器「詳細信息」,並在其中打印關於所選項目的詳細信息。 我試圖用indexpath.row跟蹤選定的項目,但是每當我執行搜索時,通常indexpath.row都會自動更改。 因此,我卡住了,如何將所選行中的唯一變量傳遞給細節VC。我真的希望有人會花時間閱讀代碼,因爲同樣的錯誤,我已經被困了近2周。 的的tableView被分配到類:AuthorVC 查看被分配到類的細節:詳細

Details.m如何將選定單元格的詳細信息發送到另一個視圖控制器

// 
// Details.m 
// AuthorsApp 
// 
// Created by georges ouyoun on 7/17/12. 
// Copyright (c) 2012 __MyCompanyName__. All rights reserved. 
// 

#import "Details.h" 
#import "Author.h" 
#import "AuthorVC.h" 
#import <sqlite3.h> 

@interface Details() 

@end 

@implementation Details 
@synthesize Favo; 
@synthesize labelText; 
@synthesize selectedAuthors; 
@synthesize author , infoRequest; 

BOOL PAss = NO; 
BOOL SElected2 = NO; 

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil 
{ 
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 




- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 
//  authorNAme = author.genre; 
// self.labelText.text =authorNAme; 
    // Do any additional setup after loading the view. 



    // self.labelText.text = @"nlsdjhfl";//*[self.author.genre description];*/ 
    // NSLog(author.genre); 




    /*   This is where the label text APPearsssssssss     */ 


    NSLog(@"Everything is ok now !"); 
    // NSLog(authorNAme); 

} 
- (void)viewDidUnload 
{ 
    // [self setLabelText:nil]; 
    NSLog(@"U have entered view did unload"); 
    [AddBut release]; 
    AddBut = nil; 
    [super viewDidUnload]; 

    [self setLabelText:Nil]; 
    [authorNAme release]; 

    // Release any retained subviews of the main view. 
} 


/* 
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 

    if ([segue.identifier isEqualToString:@"AuthorsCell"]) { 

     [segue.destinationViewController setLabelText:author.title]; 

    } 


} 



*/ 


-(void)viewWillAppear:(BOOL)animated 
{ 

    //labelText.text = authorNAme; 

    NSLog(@"U have entered the viewWillAppear tag"); 

    // detailsLabel.text = food.description; 
    //authorNAme=Nil; 
    //[self setauthorName:Nil]; 
} 

/* 
-(void) viewDidAppear:(BOOL)animated{ 

    labelText.text = @"This is the DidAppearTag"; 

    NSLog(@"U have entered the viewDidAppear tag"); 


} 

*/ 

-(void) viewWillDisappear:(BOOL)animated{ 


    NSLog(@"This is the view will disappear tag"); 

    //authorNAme.release; 


} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    return YES; 
} 

- (void)dealloc { 
    [labelText release]; 
    [AddBut release]; 
    [super dealloc]; 
} 


- (IBAction)AddButClick:(UIButton *)sender { 



    [AddBut setImage:[UIImage imageNamed:@"apple-logo copy.png"] forState:UIControlStateSelected]; 
    [AddBut setImage:[UIImage imageNamed:@"apple-logo copy.png"] forState:UIControlStateHighlighted]; 
    Favo = [[NSMutableArray alloc] initWithCapacity:1000000]; 

    NSLog(authorNAme); 

    @try { 
     NSFileManager *fileMgr = [NSFileManager defaultManager]; 
     // NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"dictionary.sqlite"]; 
     //NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"authorsDb2.sqlite"]; 
     //  NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"FinalDb.sqlite"]; 
     //NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"xxJuridique-FINAL-OK.sqlite"]; 

     NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"data.sqlite"]; 

     BOOL success = [fileMgr fileExistsAtPath:dbPath]; 
     if(!success) 
     { 
      NSLog(@"Cannot locate database file '%@'.", dbPath); 
     } 
     if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)) 
     { 
      NSLog(@"An error has occured: %@", sqlite3_errmsg(db)); 

     } 


     // const char *sql = "SELECT F_Keyword FROM wordss"; 
     const char *sql = "SELECT * FROM Sheet1"; 
     NSLog(@"Successfully selected from database"); 
     sqlite3_stmt *sqlStatement; 
     if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) 
     { 
      NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db)); 


     }else{ 


      NSLog(@"Got in the else tag"); 

      while (sqlite3_step(sqlStatement)==SQLITE_ROW /*&& PAss == NO*/) { 


       NSLog(@"Got in the while tag"); 

       Author * author = [[Author alloc] init]; 
       NSLog(@"Author initialized"); 

       author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,10)]; 
       NSLog(@"Initialization ok"); 
      //  NSLog(author.name); 

       if(/*author.name == @"NO" &&*/ HighLighted == NO){ 
        //const char *sql2 = "INSERT INTO Sheet1 "; 

        [AddBut setImage:[UIImage imageNamed:@"apple-logo copy.png"] forState:UIControlStateNormal]; 
        NSLog(@"We have not selected it as fav yet"); 
        // [AddBut setSelected:NO]; //btn changes to normal state 
        NSLog(@"The button was NOt highlighted and now is"); 
        HighLighted = YES; 
        // PAss = YES; 
        // [self release]; 
        break; 


       } 

       else 
       { 

        NSLog(@"We have selected it as fav"); 

        [AddBut setImage:[UIImage imageNamed:@"apple-logo.png"] forState:UIControlStateNormal]; 
        [AddBut setSelected:NO]; //btn changes to normal state 
        NSLog(@"The button was highlighted and now is NOt"); 


        HighLighted = NO; 
        break; 

        // [self viewDidLoad]; 
        // PAss = YES; 

       } 
     //  [Favo release]; 

     //  NSLog(Favo); 

//    author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)]; 
//    author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)]; 
//    author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)]; 
//    [theauthors addObject:author]; 
      } 
     } 
    } 
    @catch (NSException *exception) { 

     NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db)); 

    } 
    @finally { 
     // sqlite3_finalize(sqlStatement); 
     sqlite3_close(db); 

     return Favo; 
    } 





    // [AddBut setSelected:YES]; 

// if(SElected == YES){ 
//  NSLog(@"The button was highlighted and now not"); 
//   
//  [AddBut setImage:[UIImage imageNamed:@"apple-logo.png"] forState:UIControlStateNormal]; 
//  [AddBut setSelected:NO]; //btn changes to highlighted åstate 
//  SElected = NO; 
//   
//   } 
//  
// else{ 
//  
//  [AddBut setSelected:YES]; //btn changes to normal state 
//  NSLog(@"The button was NOt highlighted and now is"); 
//  SElected = YES; 
//  
// } 

} 
@end 

AuthorVC.m

#import "AuthorVC.h" 
#import "Author.h" 
#import <sqlite3.h> 
#import "SearchVC.h" 
//#import "DetailViewController.h" 
#import "Details.h" 





@implementation AuthorVC 

@synthesize theauthors; 
@synthesize author; 
NSString *authorNAme; 


- (id)initWithStyle:(UITableViewStyle)style 
{ 
    self = [super initWithStyle:style]; 
    if (self) { 
     // Custom initialization 
    } 
    return self; 
} 

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

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

#pragma mark - View lifecycle 

- (void)viewDidLoad 
{ searchBar.delegate = (id)self; 
    [self authorList]; 
    [super viewDidLoad]; 



} 

- (void)viewDidUnload 
{ 
    [searchBar release]; 
    searchBar = nil; 
    [super viewDidUnload]; 
    // Release any retained subviews of the main view. 
    // e.g. self.myOutlet = nil; 
} 

- (void)viewWillAppear:(BOOL)animated 
{ 
    [super viewWillAppear:animated]; 
} 

- (void)viewDidAppear:(BOOL)animated 
{ 
    [super viewDidAppear:animated]; 
} 

- (void)viewWillDisappear:(BOOL)animated 
{ 
    [super viewWillDisappear:animated]; 

} 

- (void)viewDidDisappear:(BOOL)animated 
{ 
    [super viewDidDisappear:animated]; 
} 

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
{ 
    // Return YES for supported orientations 
    return (interfaceOrientation == UIInterfaceOrientationPortrait); 
} 



-(void)searchBar:(UISearchBar*)searchBar textDidChange:(NSString*)text 
{ 
    if(text.length == 0) 
    { 
     isFiltered = FALSE; 
    } 
    else 
    { 
     isFiltered = true; 
     filteredTableData = [[NSMutableArray alloc] init]; 

     for (Author* author in theauthors) 
     { //[NSPredicate predicateWithFormat:@"SELECT * from books where title LIKE %@", searchBar.text]; 
      NSRange nameRange = [author.name rangeOfString:text options:NSAnchoredSearch]; 
      NSRange descriptionRange = [author.genre rangeOfString:text options:NSAnchoredSearch]; 
      if(nameRange.location != NSNotFound || descriptionRange.location != NSNotFound) 
      { 
       [filteredTableData addObject:author]; 

      } 
     } 
    } 

    [self.tableView reloadData]; 
} 





#pragma mark - Table view data source 

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

    // Return the number of sections. 
    return 1; 
} 

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

    int rowCount; 
    if(self->isFiltered) 
     rowCount = filteredTableData.count; 
    else 
     rowCount = theauthors.count; 

    return rowCount; 
    // Return the number of rows in the section. 
    //return [self.theauthors count]; 
} 
/* 

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{ 
    // NSString *Title; 
    // Author *auth = (Author*)segue.destinationViewController; 
    Details *dv = (Details*)segue.destinationViewController; 
    dv.labelText.text = author.title; 
    NSLog(@"Did Enter prepareForSegue"); 
    // labelText.text = @"Hy"; 
} 
*/ 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"AuthorsCell"; 

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 
    int rowCount = indexPath.row; 

    Author *author = [self.theauthors objectAtIndex:rowCount]; 
      //(NSIndexPath *) indexPathForSelectedRow; 
    //authorNAme =; 
    if(isFiltered){ 
     author = [filteredTableData objectAtIndex:indexPath.row]; 

    // authorNAme = author.genre; 
     // NSLog(author.genre); 


    } 
    else{ 
     author = [theauthors objectAtIndex:indexPath.row]; 

     // authorNAme = author.genre; 
     // NSLog(author.genre); 

    } 


    cell.textLabel.text = author.name; 
    cell.detailTextLabel.text = author.genre; 
    //NSString *titleString = [[[NSString alloc] initWithFormat:@"Element number : %d",author.name] autorelease]; 

    return cell; 

} 


-(NSMutableArray *) authorList{ 
    theauthors = [[NSMutableArray alloc] initWithCapacity:1000000]; 
    NSMutableArray * new2 = [[NSMutableArray alloc ] initWithCapacity:100000]; 
    // authorNAme = theauthors.sortedArrayHint.description; 
    @try { 
     NSFileManager *fileMgr = [NSFileManager defaultManager]; 
     // NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"dictionary.sqlite"]; 
     //NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"authorsDb2.sqlite"]; 
    //  NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"FinalDb.sqlite"]; 
     //NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"xxJuridique-FINAL-OK.sqlite"]; 

     NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"data.sqlite"]; 

     BOOL success = [fileMgr fileExistsAtPath:dbPath]; 
     if(!success) 
     { 
      NSLog(@"Cannot locate database file '%@'.", dbPath); 
     } 
     if(!(sqlite3_open([dbPath UTF8String], &db) == SQLITE_OK)) 
     { 
      NSLog(@"An error has occured: %@", sqlite3_errmsg(db)); 

     } 


     // const char *sql = "SELECT F_Keyword FROM wordss"; 
    const char *sql = "SELECT * FROM Sheet1"; 

     sqlite3_stmt *sqlStatement; 
     if(sqlite3_prepare(db, sql, -1, &sqlStatement, NULL) != SQLITE_OK) 
     { 
     NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db)); 
     }else{ 
      while (sqlite3_step(sqlStatement)==SQLITE_ROW) { 
       Author * author = [[Author alloc] init]; 

       //NSString *authorName = author.name; 
       author.name = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,2)]; 

       author.title = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement,4)]; 
       author.genre = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement, 4)]; 
       new2 = author.genre; 

       authorNAme=author.genre;    
       //NSLog(author.genre); 
       [theauthors addObject:author]; 

      } 
    //  authorNAme = author.genre; 


       } 
    } 
    @catch (NSException *exception) { 
     NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db)); 
    } 
    @finally { 
    // sqlite3_finalize(sqlStatement);. 
    // authorNAme = nil; 
     sqlite3_close(db); 
    // authorNAme = Nil; 
     return theauthors; 
    } 


} 


- (void)dealloc { 
    [searchBar release]; 
    [super dealloc]; 
    //[authorNAme release]; 
} 



//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender { 
//  
// /* 
//  When a row is selected, the segue creates the detail view controller as the destination. 
//  Set the detail view controller's detail item to the item associated with the selected row. 
//  */ 
// if ([[segue identifier] isEqualToString:@"ShowSelectedPlay"]) { 
//   
//  NSIndexPath *selectedRowIndex = [self.tableView indexPathForSelectedRow]; 
//  Details *detailViewController = [segue destinationViewController]; 
//  detailViewController.author = [dataController objectInListAtIndex:selectedRowIndex.row]; 
// } 
//} 



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { 

    //Get the selected country 
    NSString *selectedAuthors = [theauthors objectAtIndex:indexPath.row]; 
    //NSLog(selectedAuthors); 

    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil]; 
    Details *dvController = [storyboard instantiateViewControllerWithIdentifier:@"Details"]; //Or whatever identifier you have defined in your storyboard 

    //authorNAme = selectedAuthors.description; 

     //Initialize the detail view controller and display it. 
    //Details *dvController = [[Details alloc] init/*WithNibName:@"Details" bundle:nil*/]; 

    dvController.selectedAuthors = selectedAuthors; 


// NSString *elem = [new2 objectAtIndex:0]; 


    //NSLog(dvController.labelText.text); 
// NSString *titleString = [[[NSString alloc] initWithFormat:@"Author title : %d",indexPath.row] autorelease]; 

    // NSString *titleString2 = [[new2 objectAtIndex:indexPath.row] autorelease]; 
    // NSLog(@"this is the selected row , %s",titleString2); 

    // authorNAme = titleString; 


    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! BReak point of SQL Query!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!*/ 
/* 
    @try { 

     NSFileManager *fileMgr2 = [NSFileManager defaultManager]; 


     // NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"dictionary.sqlite"]; 
     //NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"authorsDb2.sqlite"]; 
     //  NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"FinalDb.sqlite"]; 
     //NSString *dbPath = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"xxJuridique-FINAL-OK.sqlite"]; 

     NSString *dbPath2 = [[[NSBundle mainBundle] resourcePath ]stringByAppendingPathComponent:@"data.sqlite"]; 

     BOOL success = [fileMgr2 fileExistsAtPath:dbPath2]; 
     if(!success) 
     { 
      NSLog(@"Cannot locate database file '%@'.", dbPath2); 
     } 
     if(!(sqlite3_open([dbPath2 UTF8String], &db) == SQLITE_OK)) 
     { 
      NSLog(@"An error has occured: %@", sqlite3_errmsg(db)); 

     } 
     NSLog(@"access to the second DB is ok"); 


     // const char *sql = "SELECT F_Keyword FROM wordss"; 
     const char *sql2 = "SELECT field7 FROM Sheet1 WHERE field1 = 'titleString' "; 
     //NSLog(sql2); 

     sqlite3_stmt *sqlStatement2; 
     if(sqlite3_prepare(db, sql2, -1, &sqlStatement2, NULL) != SQLITE_OK) 
     { NSLog(@"Problem with prepare the db"); 
      NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db)); 
     }else{ 

    // while (sqlite3_step(sqlStatement2)==SQLITE_ACCESS_EXISTS) { 

      NSLog(@"Starting to prepare the result"); 
      Author * author2 = [[Author alloc] init]; 
      NSLog(@"Author 2 created"); 

      author2.genre2 = [NSString stringWithUTF8String:(char *) sqlite3_column_text(sqlStatement2, 7)]; 
      NSLog(@"Initialistion of author 2 is ok"); 

     //  NSLog(author2.genre); 
       // authorNAme = author2.genre; 


      [theauthors addObject:author2]; 

    // } 

     } 

    } 
    @catch (NSException *exception) { 
     NSLog(@"Problem with prepare statement: %@", sqlite3_errmsg(db)); 
    } 
    @finally { 
     // sqlite3_finalize(sqlStatement);. 
     // authorNAme = nil; 
     sqlite3_close(db); 
     // authorNAme = Nil; 
     return theauthors; 
    } 

*/ 

    UIAlertView *messageAlert = [[UIAlertView alloc] 
           initWithTitle:@"Row Selected" message:authorNAme delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil]; 

[messageAlert show]; 

    [self.navigationController pushViewController:dvController animated:YES]; 

} 


- (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath { 

    //return UITableViewCellAccessoryDetailDisclosureButton; 
    return UITableViewCellAccessoryDisclosureIndicator; 
} 

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath { 

    [self tableView:tableView didSelectRowAtIndexPath:indexPath]; 
} 



/* 

-(void) showDetailsForIndexPath:(NSIndexPath*)indexPath 
{ 
    [self->searchBar resignFirstResponder]; 
    DetailViewController* vc = [self.storyboard instantiateViewControllerWithIdentifier:@"DetailsViewController"]; 
    AuthorVC* author; 

    if(isFiltered) 
    { 
     author = [filteredTableData objectAtIndex:indexPath.row]; 
    } 
    else 
    { 
     author = [theauthors objectAtIndex:indexPath.row]; 
    } 

    vc.author = author; 
    [self.navigationController pushViewController:vc animated:true];  
} 




*/ 


@end 

回答

1

只需使用作者property在您的詳細信息中競爭w控制器。你需要將它傳遞在tableView:didSelectRowAtIndexPath:像這樣在你的showDetailsForIndexPath:

if(isFiltered) 
{ 
    author = [filteredTableData objectAtIndex:indexPath.row]; 
} 
else 
{ 
    author = [theauthors objectAtIndex:indexPath.row]; 
} 

vc.author = author; 
[self.navigationController pushViewController:vc animated:true]; 
+0

我真的不知道怎麼感謝你纔好你是一個生命的救星!謝謝你,先生!! – 2012-08-10 11:47:50

+0

不客氣! – Moxy 2012-08-10 18:15:50

+0

先生,我可以麻煩你一些,看看這個其他職位PLZ:http://stackoverflow.com/questions/11902213/keep-search-bar-fixed-position-while-scrolling-tableview – 2012-08-11 05:48:55

相關問題