解析的提要在 UITableView 上不可见,cellForRowAtIndexPath 方法未被访问

Posted

技术标签:

【中文标题】解析的提要在 UITableView 上不可见,cellForRowAtIndexPath 方法未被访问【英文标题】:parsed feed not visible on UITableView, cellForRowAtIndexPath method not getting accessed 【发布时间】:2013-04-22 05:39:41 【问题描述】:

我试图在表格视图上显示已解析的 Yahoo RSS 提要。但是屏幕上什么也没有显示。当我使用断点时,我开始知道控件根本不会使用 cellForRowAtIndexPath 方法。我不知道为什么会这样。 yahoo feed的结构如下:

 <?xml version="1.0" encoding="utf-8"?>
    <rss xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
    <title>Yahoo! News - Latest News &amp; Headlines</title>
    <link>http://news.yahoo.com/</link>
    <description>The latest news and headlines from Yahoo! News. Get breaking news stories and in-depth coverage with videos and photos.</description>
    <language>en-US</language>
    <copyright>Copyright (c) 2013 Yahoo! Inc. All rights reserved</copyright>
    <pubDate>Sun, 21 Apr 2013 17:08:00 -0400</pubDate>
    <ttl>5</ttl>
    <image>
    <title>Yahoo! News - Latest News &amp; Headlines</title>
    <link>http://news.yahoo.com/</link>
    <url>http://l.yimg.com/a/i/us/nws/th/main_142c.gif</url>
    </image>
    <item><title>After the bombings, the blame game begins</title><description>&lt;p&gt;&lt;a href="http://news.yahoo.com/boston-marathon-bombing-blame-game-begins-210800101.html"&gt;&lt;img src="http://l3.yimg.com/bt/api/res/1.2/uiv31afw5K_BzPxeYQz44Q--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9ODU7dz0xMzA-/http://media.zenfs.com/en_us/News/Reuters/2013-04-22T013026Z_741208741_GM1E94M0Q7101_RTRMADP_3_USA-EXPLOSIONS-BOSTON.JPG"    align="left" title="A couple embraces at a memorial on Boylston Street to the victims of the Boston Marathon bombings in Boston" border="0" /&gt;&lt;/a&gt;Some lawmakers fault the FBI for not following up on intelligence about one of the alleged bombers.&lt;/p&gt;&lt;br clear="all"/&gt;</description><link>http://news.yahoo.com/boston-marathon-bombing-blame-game-begins-210800101.html</link><pubDate>Sun, 21 Apr 2013 17:08:00 -0400</pubDate><source url="http://www.csmonitor.com/">Christian Science Monitor</source><guid isPermaLink="false">boston-marathon-bombing-blame-game-begins-210800101</guid><media:content url="http://l3.yimg.com/bt/api/res/1.2/uiv31afw5K_BzPxeYQz44Q--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9ODU7dz0xMzA-/http://media.zenfs.com/en_us/News/Reuters/2013-04-22T013026Z_741208741_GM1E94M0Q7101_RTRMADP_3_USA-EXPLOSIONS-BOSTON.JPG" type="image/jpeg"  ></media:content><media:text type="html">&lt;p&gt;&lt;a href="http://news.yahoo.com/boston-marathon-bombing-blame-game-begins-210800101.html"&gt;&lt;img src="http://l3.yimg.com/bt/api/res/1.2/uiv31afw5K_BzPxeYQz44Q--/YXBwaWQ9eW5ld3M7Zmk9ZmlsbDtoPTg2O3E9ODU7dz0xMzA-/http://media.zenfs.com/en_us/News/Reuters/2013-04-22T013026Z_741208741_GM1E94M0Q7101_RTRMADP_3_USA-EXPLOSIONS-BOSTON.JPG"    align="left" title="A couple embraces at a memorial on Boylston Street to the victims of the Boston Marathon bombings in Boston" border="0" /&gt;&lt;/a&gt;Some lawmakers fault the FBI for not following up on intelligence about one of the alleged bombers.&lt;/p&gt;&lt;br clear="all"/&gt;</media:text><media:credit role="publishing company"></media:credit></item></guid></channel>
</rss>

我的 feedViewController.m 如下:

@interface feedViewController ()

    @end

    @implementation feedViewController

    @synthesize tableView,showPosts;
    //@synthesize feed;

    Feed *xmlParseFeed;
    //channel *chShow;

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


    - (void)viewDidLoad
    
        [super viewDidLoad];
        //self.feed = [[Feed alloc] init];
        self.showPosts = [[NSMutableArray alloc] init];

        NSArray *newPosts = [xmlParseFeed newPosts];

        if (newPosts)    
            [self.showPosts addObjectsFromArray:newPosts];
            //[newPosts release];
        

        static NSString *feedURLString = @"http://news.yahoo.com/rss";
        NSURL *feedURL = [NSURL URLWithString:feedURLString];
        xmlParseFeed = [[Feed alloc] initWithURL:feedURL];
        self.showPosts = [[NSMutableArray alloc] init];

        [xmlParseFeed refresh];
    

    - (void)viewDidUnload
    
        [self setTableView:nil];
        [super viewDidUnload];
        // Release any retained subviews of the main view.
    
    - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
    
        return 1;
    
    - (NSInteger)tableView:(UITableView *)tableView
     numberOfRowsInSection:(NSInteger)section 

        return [showPosts count];
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
        static NSString *CellIdentifier = @"Cell";

        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) 
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] ;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;    
        

        ItemDataCollection *post = [showPosts objectAtIndex:indexPath.row];
         Feed *entry = [showPosts objectAtIndex:indexPath.row];
        // Set up the cell...
            channel *channelRecord = [self.showPosts objectAtIndex:indexPath.row];
        cell.textLabel.text = channelRecord.cTitle;
        cell.textLabel.text = channelRecord.pubDate;
        NSLog(@"channelRecord.title *****************%@",channelRecord.cTitle);    

      /*  cell.textLabel.text = post.title;
        cell.textLabel.text = post.itemDescription;
        cell.textLabel.text = post.titleImage;
        NSLog(@"item title******%@",post.title); */




        cell.textLabel.font=[UIFont fontWithName:@"Arial" size:12];
        cell.textLabel.numberOfLines = 1;





       return cell;
    
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation

    return (interfaceOrientation == UIInterfaceOrientationPortrait);


@end

Properties in channel class are: cTitle,pubDate and itemCollectionArray. Properties in Post class are: title, itemDescription and titleImage. Feed class is for parsing. the contents of Feed.m is as follows:

 @class ItemDataCollection;
    @implementation Feed
    @synthesize feedURL,feedRequest,currentElement,currentElementData;
    //@synthesize feedChannel;
    //@synthesize feedPosts;
    static ItemDataCollection *itemCollection;
    static NSMutableArray *channelCollection;
    NSMutableString *mString;
    NSMutableString *str;
    channel *Channel ;
    - (NSArray *)newPosts 
        NSMutableArray *posts = [[NSMutableArray alloc] init];

        for (NSInteger item = 1; item <= 5; item++) 
            //NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
            ItemDataCollection *newPost;
            newPost = [[ItemDataCollection alloc] init];
          // NSString *pubDate = [NSDate dateWithTimeIntervalSinceNow:@"pubDate"];
       newPost.title = [NSString stringWithFormat:@"title %@", kTitleElementName];
            newPost.itemDescription = [NSString stringWithFormat:@"itemdescription %@", kItemDescription];
            newPost.titleImage = [NSString stringWithFormat:@"image %@",kItemImage];
         //   newPost.itemTitle = [NSString stringWithFormat:@"itemtitle %@", ITEM_TITLE_XML];

            [posts addObject:newPost];
            //[newPost release];

           // [pool drain];
        
        return posts;
    


    - (Feed *) initXMLParser 

        //[super init];

        appDelegate = (appAppDelegate *)[[UIApplication sharedApplication] delegate];

        return self;
    
    -(id)initWithURL:(NSURL *)sourceURL 
        if (self = [super init])   
             self.feedURL = sourceURL;

            channelCollection=[[NSMutableArray alloc] init];
        
        return self;
    
    - (void)refresh 
        self.feedRequest = [ASIHTTPRequest requestWithURL:feedURL];

      //  [feedPosts removeAllObjects];
        [feedRequest setDelegate:self];
        [feedRequest startAsynchronous];
    
    - (void)requestFinished:(ASIHTTPRequest *)request 
        NSData *responseData = [request responseData];
       // NSLog(@"*************response are *********%@",[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);

        NSXMLParser *parser = [[NSXMLParser alloc] initWithData:responseData];
        [parser setDelegate:self];
        if ([parser parse]) 

            [[NSNotificationCenter defaultCenter] 
             postNotificationName:@"myevent"
             object:nil];
           // [posts ]

            
    

    - (void)requestFailed:(ASIHTTPRequest *)request 
        NSError *error = [request error];
        NSLog(@"requestFailed: %@", [error localizedDescription]);
     

    - (void)parser:(NSXMLParser *)parser
    didStartElement:(NSString *)elementName
      namespaceURI:(NSString *)namespaceURI
     qualifiedName:(NSString *)qName
        attributes:(NSDictionary *)attributeDict 

        if ([elementName isEqualToString:kChannelElementName]) 
            Channel = [[channel alloc] init];
            dict=[[NSMutableDictionary alloc] init];
            [Channel setItemCollectionArray:[[NSMutableArray alloc] init]];


            return ;
    

        if ([elementName isEqualToString:kItemElementName]) 
           itemCollection=[[ItemDataCollection alloc] init];


            return ;
         
        if ([elementName isEqualToString:kTitleElementName]) 


            return ;

        
      if([elementName isEqualToString:kItemDescription])
            return ;
        
        if ([elementName isEqualToString:kItemImage]) 
            NSString *urlString = attributeDict[@"url"];
            if(urlString)
                [dict setObject:urlString forKey:@"img"];
                NSLog(@"%@",urlString);
                mString = [NSString stringWithFormat:urlString];
                str = [NSString stringWithFormat:mString];
            

            return ;
        

    

    - (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string 

        if (currentElementData == nil) 
            self.currentElementData = [[NSMutableString alloc] init];
        

        [currentElementData appendString:string];     
    
    - (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName
      namespaceURI:(NSString *)namespaceURI
     qualifiedName:(NSString *)qName 

        if ([elementName isEqualToString:kChannelElementName]) 
            [channelCollection addObject:Channel];

            NSLog(@"channel are***********%@",channelCollection);
            for(ItemDataCollection *mydata in Channel.itemCollectionArray)
                NSLog(@"___%@ <><><><><> desc \n   <><><><><><> img \n        %@",mydata.title,/*mydata.itemDescription*/mydata.titleImage);

            

            Channel =nil;

        

       else  if ([elementName isEqualToString:kItemElementName]) 
           [[Channel itemCollectionArray] addObject:itemCollection];
           itemCollection=nil;

            
       else  if ([elementName isEqualToString:kTitleElementName]) 
           if(itemCollection==nil)

           Channel.cTitle=currentElementData;
           
           else

               itemCollection.title=currentElementData;

           



       
       else  if ([elementName isEqualToString:kPubDate]) 
           Channel.pubDate=currentElementData;


       
      else  if ([elementName isEqualToString: kItemDescription]) 
          if(itemCollection!=nil)
           itemCollection.itemDescription = currentElementData;


        
      
      else if([currentElementData rangeOfString:@"media:content"].location)

          if(itemCollection!=nil)

          if([str isEqualToString:mString])
                //  [currentElementData appendString:dict];
                  itemCollection.titleImage = mString;
           else
              itemCollection.titleImage = @"";
          
          
      



        self.currentElementData = nil;
    
    - (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError 

        NSString *info = [NSString stringWithFormat:
                          @"Error %i, Description: %@, Line: %i, Column: %i",
                          [parseError code],
                          [[parser parserError] localizedDescription],
                          [parser lineNumber],
                          [parser columnNumber]];

        NSLog(@"RSS Feed Parse Error: %@", info);
    

    @end

Feed 正在被解析,可以在控制台上看到。但它在屏幕上不可见。可能是什么原因?正如我之前所说, cellForRowAtIndexPath() 根本没有被访问。这是什么原因??

我已经添加了这个方法:

- (void)feedChanged:(NSNotification *)notification 
    NSArray *newPosts = [xmlParseFeed newPosts];

    NSLog(@"%@",newPosts);
    if (newPosts) 

        [self.showPosts addObjectsFromArray:newPosts];
        [self.tableView reloadData];
       // [self updateViewTitle];
       // [newPosts release];
   

【问题讨论】:

一旦检查数组 newPosts 是否具有值并将数据源添加到 tableview? 您是否正确设置了代表@Crazed'nDazed 我在 viewDidLoad() 中打印了 newPosts,它显示为 null.... 为什么会这样?数据源和委托已使用故事板设置。 【参考方案1】:

我看不到您在代码中的哪个位置从 UITableView 调用 reloadData。您需要在加载 newPosts 之后调用此方法。

如果这不起作用,请检查以下几项:

    tableView:numberOfRowsInSection: 返回的值是多少?它大于零吗?如果它为零,这就是为什么不调用 tableView:cellForRowAtIndexPath 的原因。

    如何加载 Feed?是在主线程还是其他线程?您应该在不同的线程中加载它,因此在加载数据时不会阻塞 UI,但请确保在将数据加载到 newPosts 后调用 reloadData。

【讨论】:

以上是关于解析的提要在 UITableView 上不可见,cellForRowAtIndexPath 方法未被访问的主要内容,如果未能解决你的问题,请参考以下文章

UIButton 在 TableView 单元格中不可见

UITableView 标头不可见

MapKit 自定义注释被添加到地图,但在地图上不可见

第一个屏幕上不可见的单元格不可点击

UITableView 中的阴影不一致

拉动刷新uitableview json解析数据