2013-05-16 3 views
2

Когда я нажимаю на поиск, он выполняет класс поиска, и после нахождения результатов он выполняет метод numberOfRows, но затем показывает пустую таблицу. Он не выполняет метод cellForRowAtIndexPath. проверить мой код нижеМетод UITableview cellForRowAtIndexPath не выполняется?

код viewcontroller.h

, когда я нажимаю кнопку поиска этот метод будут выполнены

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{ 
    SearchResultsViewController *searchRes=[[SearchResultsViewController alloc]initWithNibName:@"SearchResultsViewController" bundle:nil]; 
    NSString *searchQuery=[search text]; 
    sharedManager=[Mymanager sharedManager]; 
    sharedManager.searchQuery=searchQuery; 

    [searchRes searchString:searchQuery]; 


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

} 

в поисках класса

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{ 
    NSLog(@"%@",results); 
      return [results count]; 

} 

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

    UITableViewCell *cell = [tableView1 dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 

    cell.textLabel.adjustsFontSizeToFitWidth = YES; 

     NSLog(@"indexpath%d",indexPath.row); 
     NSLog(@"%@",[results objectAtIndex:[indexPath row]]); 

     SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]]; 
     NSLog(@"%@",hit.neighboringText); 
     cell.textLabel.text = [NSString stringWithFormat:@"...%@...", hit.neighboringText]; 
     cell.detailTextLabel.text = [NSString stringWithFormat:@"Chapter %d - page %d", hit.chapterIndex, hit.pageIndex+1]; 
     cell.textLabel.font = [UIFont fontWithName:@"Trebuchet MS" size:12]; 
     cell.textLabel.textColor = [UIColor colorWithRed:25/255.0 green:90/255.0 blue:100/255.0 alpha:1]; 

// else 
// { 
//   
// } 
    // [[self resultsTableView] reloadData]; 
    return cell; 
} 

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

     SearchResult* hit = (SearchResult*)[results objectAtIndex:[indexPath row]]; 

    [fvc loadSpine:hit.chapterIndex atPageIndex:hit.pageIndex highlightSearchResult:hit]; 


} 


- (void) searchString:(NSString*)query{ 
// if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) 
// { 
    self.results = [[NSMutableArray alloc] init]; 
    [resultsTableView reloadData]; 
    currentQuery=sharedManager.searchQuery; 
//  
    [self searchString:currentQuery inChapterAtIndex:0]; 
// 
// }else { 
// currentQuery=sharedManager.searchQuery; 
// [self searchString:currentQuery inChapterAtIndex:0]; 
//} 
} 

- (void) searchString:(NSString *)query inChapterAtIndex:(int)index{ 

      currentChapterIndex = index; 
    sharedManager=[Mymanager sharedManager]; 
    Chapter* chapter = [sharedManager.spineArray objectAtIndex:index]; 
    NSLog(@"%d",chapter.text.length); 
    NSRange range = NSMakeRange(0, chapter.text.length); 

    NSLog(@"%@",sharedManager.searchQuery); 
     range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil]; 
    int hitCount=0; 
    while (range.location != NSNotFound) { 
     range = NSMakeRange(range.location+range.length, chapter.text.length-(range.location+range.length)); 
     range = [chapter.text rangeOfString:sharedManager.searchQuery options:NSCaseInsensitiveSearch range:range locale:nil]; 
     hitCount++; 
    } 

    if(hitCount!=0){ 
     UIWebView* webView = [[UIWebView alloc] initWithFrame:chapter.windowSize]; 
     [webView setDelegate:self]; 
     NSURLRequest* urlRequest = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:chapter.spinePath]]; 
     [webView loadRequest:urlRequest]; 
    } else { 
     if((currentChapterIndex+1)<[sharedManager.spineArray count]){ 
      [self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)]; 
     } else { 
      fvc.searching = NO; 
     } 
    } 



} 





-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
    return 1; 
} 

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{ 
    NSLog(@"%@", error); 
    [webView release]; 
} 

- (void) webViewDidFinishLoad:(UIWebView*)webView{ 
    NSString *varMySheet = @"var mySheet = document.styleSheets[0];"; 

    NSString *addCSSRule = @"function addCSSRule(selector, newRule) {" 
    "if (mySheet.addRule) {" 
    "mySheet.addRule(selector, newRule);"        // For Internet Explorer 
    "} else {" 
    "ruleIndex = mySheet.cssRules.length;" 
    "mySheet.insertRule(selector + '{' + newRule + ';}', ruleIndex);" // For Firefox, Chrome, etc. 
    "}" 
    "}"; 


    NSString *insertRule1 = [NSString stringWithFormat:@"addCSSRule('html', 'padding: 0px; height: %fpx; -webkit-column-gap: 0px; -webkit-column-width: %fpx;')", webView.frame.size.height, webView.frame.size.width]; 
    NSString *insertRule2 = [NSString stringWithFormat:@"addCSSRule('p', 'text-align: justify;')"]; 




     NSString *setTextSizeRule = [NSString stringWithFormat:@"addCSSRule('body', '-webkit-text-size-adjust: %d%%;')",[[sharedManager.spineArray objectAtIndex:currentChapterIndex] fontPercentSize]]; 

    [webView stringByEvaluatingJavaScriptFromString:varMySheet]; 

    [webView stringByEvaluatingJavaScriptFromString:addCSSRule]; 

    [webView stringByEvaluatingJavaScriptFromString:insertRule1]; 

    [webView stringByEvaluatingJavaScriptFromString:insertRule2]; 

     [webView stringByEvaluatingJavaScriptFromString:setTextSizeRule]; 
    [webView highlightAllOccurencesOfString:sharedManager.searchQuery]; 

    NSString* foundHits = [webView stringByEvaluatingJavaScriptFromString:@"results"]; 

     NSLog(@"%@", foundHits); 

    NSMutableArray* objects = [[NSMutableArray alloc] init]; 

    NSArray* stringObjects = [foundHits componentsSeparatedByString:@";"]; 
    for(int i=0; i<[stringObjects count]; i++){ 
     NSArray* strObj = [[stringObjects objectAtIndex:i] componentsSeparatedByString:@","]; 
     if([strObj count]==3){ 
      [objects addObject:strObj]; 
     } 
    } 

    NSArray* orderedRes = [objects sortedArrayUsingComparator:^(id obj1, id obj2){ 
     int x1 = [[obj1 objectAtIndex:0] intValue]; 
     int x2 = [[obj2 objectAtIndex:0] intValue]; 
     int y1 = [[obj1 objectAtIndex:1] intValue]; 
     int y2 = [[obj2 objectAtIndex:1] intValue]; 
     if(y1<y2){ 
      return NSOrderedAscending; 
     } else if(y1>y2){ 
      return NSOrderedDescending; 
     } else { 
      if(x1<x2){ 
       return NSOrderedAscending; 
      } else if (x1>x2){ 
       return NSOrderedDescending; 
      } else { 
       return NSOrderedSame; 
      } 
     } 
    }]; 

    [objects release]; 
    NSLog(@"%@",currentQuery); 


    for(int i=0; i<[orderedRes count]; i++){ 
     NSArray* currObj = [orderedRes objectAtIndex:i]; 

     SearchResult* searchRes = [[SearchResult alloc] initWithChapterIndex:currentChapterIndex pageIndex:([[currObj objectAtIndex:1] intValue]/webView.bounds.size.height) hitIndex:0 neighboringText:[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"unescape('%@')", [currObj objectAtIndex:2]]] originatingQuery:currentQuery]; 
     [results addObject:searchRes]; 
     NSLog(@"%@",results); 

    [searchRes release]; 
    } 


    //Print results 

    for(int i=0;i<[results count];i++) 
    { 
     SearchResult* hit = (SearchResult*)[results objectAtIndex:i]; 
     NSLog(@"%@",hit.neighboringText); 
    } 


    [resultsTableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO]; 
    if((currentChapterIndex+1)<[sharedManager.spineArray count]){ 
     [self searchString:sharedManager.searchQuery inChapterAtIndex:(currentChapterIndex+1)]; 
    } else { 
     fvc.searching= NO; 
    } 


    [[self resultsTableView] reloadData]; 
} 



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

//- (void)dealloc 
////{ 
//// self.resultsTableView = nil; 
//// //[results release]; 
//// //[currentQuery release]; 
//// [super dealloc]; 
//} 

- (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 
{ 
    [super viewDidLoad]; 
    resultsTableView=[[UITableView alloc]init]; 
    [resultsTableView setDelegate:self]; 
    [resultsTableView setDataSource:self]; 

    sharedManager=[Mymanager sharedManager]; 
    // Do any additional setup after loading the view from its nib. 
    results = [[NSMutableArray alloc] init]; 

    [email protected]"Search "; 
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc] 
            initWithTitle:@"Back" 
            style:UIBarButtonItemStylePlain 
            target:nil 
            action:nil]; 
    self.navigationItem.backBarButtonItem=backButton; 

    [[UINavigationBar appearance] setTitleTextAttributes: @{ 
           UITextAttributeTextColor: [UIColor whiteColor], 
          UITextAttributeTextShadowColor: [UIColor lightGrayColor], 
         UITextAttributeTextShadowOffset: [NSValue valueWithUIOffset:UIOffsetMake(0.0f, 1.0f)], 
            UITextAttributeFont: [UIFont fontWithName:@"Trebuchet MS" size:15.0f] 
    }]; 


    noMatchingSearch=[[NSArray alloc]initWithObjects:@"No Element Found", nil]; 

    tableOfContents=[[NSMutableArray alloc]init]; 
    for (id img in search.subviews) 
    { 
     if ([img isKindOfClass:NSClassFromString(@"UISearchBarBackground")]) 
     { 
      [img removeFromSuperview]; 
     } 
    } 

    tableOfContents=[sharedManager.List copy]; 

} 

- (void)viewDidUnload 
{ 
    search = nil; 
    [super viewDidUnload]; 
     // Release any retained subviews of the main view. 
    self.resultsTableView = nil; 
} 

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

МОЯ РЕЗУЛЬТАТЫ ПОИСКА

"<SearchResult: 0x113482c0>", 
"<SearchResult: 0x11348a20>", 
"<SearchResult: 0x88c0a50>" 
+0

чек не из строки в вашем методе numberOfRowsInSection. log your [results count] ... –

+0

, но'numberOfSections 'и'numberOfRowsInSection'> 0, не так ли? – geo

+0

оба больше нуля Число строк примерно равно 22, а раздел равен 1 –

ответ

0

Проблема с методом поиска перед поиска в массиве не реинициализирован и, следовательно, 0 возвращается в resultArray и, следовательно, никакого значения в таблицах

- (void) searchString:(NSString*)query{ 
    self.results = [[NSMutableArray alloc] init];//Here it becomes 0!! 
    [resultsTableView reloadData]; 
    currentQuery=sharedManager.searchQuery; 
} 

Чтобы сделать это правильно, После того, как выполняется поиск Я считаю, что

[self searchString:currentQuery inChapterAtIndex:0]; 

Загрузить значение в массиве результатов и затем перезагрузить таблицу.

Убедитесь

в .h добавить

<UITableViewDataSource,UITableViewDelegate> 

в СИБ

соединять источник данных и делегирует [если через СИБ]

+0

oh..ok я удалю этот код –

+0

no, no..see мой отредактированный ответ –

+0

[[self tablename] reloaddata]; достаточно ryt –

Смежные вопросы