ios - NSXMLParser 的 nil 输出问题

标签 ios objective-c xml nsxmlparser null

我正在使用 NSXMLParser 解析博客中的 RSS2 提要,以在 TableView 中输入数据。在我下面的代码中,我在接收 pubDate 的“nil”和 XML 的描述标签时遇到问题。下面是我的 XML 和代码,以及我的 ViewController。

XML:

<item>
<title>Back-to-school issue of Blue and Gold in the mail</title>
<link>http://cazhigh.com/caz/gold/?p=2896</link>
<comments>http://cazhigh.com/caz/gold/?p=2896#comments</comments>
<pubDate>Thu, 29 Aug 2013 12:35:40 +0000</pubDate>
<dc:creator>
<![CDATA[ Laura Ryan ]]>
</dc:creator>
<category>
<![CDATA[ District Office News ]]>
</category>
<category>
<![CDATA[ News ]]>
</category>
<category>
<![CDATA[ Blue & Gold ]]>
</category>
<guid isPermaLink="false">http://cazhigh.com/caz/gold/?p=2896</guid>
<description>
<![CDATA[
<img width="150" height="150" src="http://cazhigh.com/caz/gold/wp-content/uploads/2013/08/BluGold_BacktoSchool2013_cover-150x150.jpg" class="attachment-thumbnail wp-post-image" alt="Blue and Gold (Back to School 2013)" style="display: block; margin-bottom: 5px; clear:both;" />Be on the lookout for the September 2013 edition of the Blue and Gold newsletter, which should be arriving in the mail soon.  Included in the newsletter are district policies and notifications that we urge you to review, become familiar with and keep for your reference throughout the school year. The issue also provides some [&#8230;]
]]>
</description>
<content:encoded>
<![CDATA[
<img width="150" height="150" src="http://cazhigh.com/caz/gold/wp-content/uploads/2013/08/BluGold_BacktoSchool2013_cover-150x150.jpg" class="attachment-thumbnail wp-post-image" alt="Blue and Gold (Back to School 2013)" style="display: block; margin-bottom: 5px; clear:both;" /><div id="attachment_289
]]>
<![CDATA[
8" style="width: 241px" class="wp-caption alignright"><a href="http://cazhigh.com/caz/gold/wp-file-browser-top/blueandgold/Blue%20and%20Gold%20(September%202013)"><img class="size-medium wp-image-2898 " alt="Blue and Gold (Back to School 2013)" src="http://cazhigh.com/caz/gold/wp-content/uploads/2013/08/BluGold_BacktoSchool2013_cover-231x300.jpg" width="231" height="300" /></a><p class="wp-caption-text">Blue and Gold (Back to School 2013)</p></div> <p itemprop="name"><span style="font-size: 13px;">Be on the lookout for the September 2013 edition of the Blue and Gold newsletter, which should be arriving in the mail soon. </span></p> <div itemprop="description articleBody"> <p>Included in the newsletter are district policies and notifications that we urge you to review, become familiar with and keep for your reference throughout the school year.</p> <p>The issue also provides some updates on work undertaken in Cazenovia schools — on everything from curricula to facilities — over the summer break, as well as &#8220;welcome back&#8221; messages from Superintendent of Schools Robert S. Dubik, Cazenovia High School Principal Eric Schnabl and Assistant Principal Susan Vickers, Cazenovia Middle School Principal Jean Regan and Burton Street Elementary Principal Mary-Ann MacIntosh.</p> <p>If you have questions related to the policies or notifications included in the newsletter, please call the district office at (315) 655-1317.</p> <p>The newsletter is also <span style="color: #000080;"><a title="link to Blue and Gold (September 2013)" href="http://cazhigh.com/caz/gold/wp-file-browser-top/blueandgold/Blue%20and%20Gold%20(September%202013)" target="_blank"><span style="color: #000080;"><b>available online</b></span></a></span>.</p> </div>
]]>

ViewContoller.h

#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>

@interface FeedController2 : UIViewController <UITableViewDataSource, UITableViewDelegate, NSXMLParserDelegate, UIWebViewDelegate>{
    NSXMLParser *xmlparser;
    NSString *classelement;
    NSMutableArray *titarry;
    NSMutableArray *linkarray;
    NSMutableArray *datearray;
    NSMutableArray *descarray;
    bool itemselected;
    NSMutableString *mutttitle;
    NSMutableString *mutstrlink;
    NSMutableString *mutstrdate;
    NSMutableString *mutstrdesc;
}

@property (nonatomic, weak) IBOutlet UITableView* feedTableView;
//@property(nonatomic, retain) NSMutableString *currentValue;
//@property(nonatomic) NSUInteger dataElementType;
//@property(nonatomic, retain) NSDateFormatter *theDateFormatter;

@end

ViewContoller.m

- (void)viewDidLoad
{
    [super viewDidLoad];


    titarry=[[NSMutableArray alloc] init];
    linkarray=[[NSMutableArray alloc] init];
    NSString *rssaddr=@"http://cazhigh.com/caz/gold/?feed=rss2";
    NSURL *url=[NSURL URLWithString:rssaddr];
    xmlparser =[[NSXMLParser alloc] initWithContentsOfURL:url];
    [xmlparser setDelegate:self];
    [xmlparser parse];

    NSString* boldFontName = @"GillSans-Bold";
    [self styleNavigationBarWithFontName:boldFontName];
    self.title = @"Blog Feed";

    self.feedTableView.dataSource = self;
    self.feedTableView.delegate = self;
    self.feedTableView.backgroundColor = [UIColor whiteColor];
    self.feedTableView.separatorColor = [UIColor colorWithWhite:0.9 alpha:0.6];
}

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

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    //return [titarry count];
    if(titarry.count <= 5){
        return titarry.count;
    }else{
        return 5;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    static NSString *CellIdentifier = @"FeedCell2";

    FeedCell2* cell = [tableView dequeueReusableCellWithIdentifier:@"FeedCell2"];

    if (cell == nil) {
        cell = [[FeedCell2 alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] ;
    }
    NSString *RSSTitle = nil;
    RSSTitle = [titarry objectAtIndex:indexPath.row];
    RSSTitle = [RSSTitle substringToIndex:[RSSTitle length] - 3];
    cell.nameLabel.text = RSSTitle;
    cell.dateLabel.text = [datearray objectAtIndex:indexPath.row];
    NSString *desc = [descarray objectAtIndex:indexPath.row];
    cell.updateLabel.text = desc;
    NSLog(@" Date: %@", mutstrdate);
    NSLog(@"ARRAY: %@", datearray);
    NSLog(@"Title: %@", [titarry objectAtIndex:indexPath.row]); //Log title from array
    NSLog(@"Date Posted: %@", [datearray objectAtIndex:indexPath.row]);//Log date posted
    NSLog(@"Link Address: %@", [linkarray objectAtIndex:indexPath.row]); //Log link address
    cell.accessoryType=UITableViewCellSelectionStyleBlue;
    return cell;
    /*
    if(indexPath.row % 2){

        FeedCell2* cell = [tableView dequeueReusableCellWithIdentifier:@"FeedCell2"];

        cell.nameLabel.text = @"Laura Leamington";
        cell.updateLabel.text = @"This is a pic I took while on holiday on Wales. The weather played along nicely which doesn't happen often";

        cell.dateLabel.text = @"1 hr ago";
        cell.likeCountLabel.text = @"293 likes";
        cell.commentCountLabel.text = @"55 comments";

        NSString* profileImageName = self.profileImages[indexPath.row%self.profileImages.count];
        cell.profileImageView.image = [UIImage imageNamed:profileImageName];

        return cell;
    }
    else{

        FeedCell2* cell = [tableView dequeueReusableCellWithIdentifier:@"FeedCell2-Pic"];

        cell.nameLabel.text = @"John Keynetown";
        cell.updateLabel.text = @"On the trip to San Fransisco, the Golden gate bridge looked really magnificent. This is a city I would love to visit very often.";

        cell.dateLabel.text = @"1 hr ago";
        cell.likeCountLabel.text = @"134 likes";
        cell.commentCountLabel.text = @"21 comments";

        NSString* profileImageName = self.profileImages[indexPath.row%self.profileImages.count];
        cell.profileImageView.image = [UIImage imageNamed:profileImageName];

        cell.picImageView.image = [UIImage imageNamed:@"feed-bridge.jpg"];

        return cell;
    }
     */
}


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

    /*
    NSArray *nibArray2 = [[NSBundle mainBundle] loadNibNamed:@"iPhoneSecondPage" owner:self options:nil];
    iPhoneSecondPageView *secondPageView = (iPhoneSecondPageView *)[nibArray2 objectAtIndex:0];
    [secondPageView.powerSchoolButton addTarget:self action:@selector(powerSchoolSegue) forControlEvents:UIControlEventTouchUpInside];
    */

    XMLViewController *second = [[XMLViewController alloc] initWithNibName:@"XMLViewController" bundle:nil];
    [self.navigationController pushViewController:second animated:YES];
    NSLog(@"Link: %@", [linkarray objectAtIndex:indexPath.row]);
    NSURL *url=[NSURL URLWithString:[linkarray objectAtIndex:indexPath.row]];
    NSURLRequest *req=[NSURLRequest requestWithURL:url];
    second.XMLWebView.scalesPageToFit=YES;
    [second.XMLWebView loadRequest:req];//here we have to perform changes try to do some things here

}


-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{

    return (indexPath.row % 2) ? 125 : 251;
}

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

    classelement=elementName;

    if([elementName isEqualToString:@"item"])
    {
        itemselected=YES;
        mutttitle=[[NSMutableString alloc] init];
        mutstrlink=[[NSMutableString alloc] init];
        mutstrdate=[[NSMutableString alloc] init];
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName;
{
    if([elementName isEqualToString:@"item"])
    {
        itemselected=NO;

        [titarry addObject:mutttitle];
        [linkarray addObject:mutstrlink];
        [datearray addObject:mutstrdate];
        [descarray addObject:mutstrdesc];

    }

}


- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string;
{
    if (itemselected)
    {

        if ([classelement isEqualToString:@"title"])
        {
            [mutttitle appendString:string];
        }
        else if ([classelement isEqualToString:@"link"])
        {
            [mutstrlink appendString:string];
        }
        else if ([classelement isEqualToString:@"pubDate"])
        {
            [mutstrdate appendString:string];
        }
        else if ([classelement isEqualToString:@"description"])
        {
            [mutstrdesc appendString:string];
        }

    }
}

- (void)parser:(NSXMLParser *)parser parseErrorOccurred:(NSError *)parseError;
{
    UIAlertView *alt=[[UIAlertView alloc] initWithTitle:@"RSS Reader"
                                                message:[NSString stringWithFormat:@"%@",parseError]
                                               delegate:nil
                                      cancelButtonTitle:@"Close"
                                      otherButtonTitles:nil];

    [alt show];


}

最佳答案

在您提供的代码中,您遗漏了两件事:

  1. 结束你的 xml 部分 ( </content:encoded></item> )
  2. 数组变量的初始化:datearray, descarray

如果您不在实际代码中也初始化数组,那么您尝试放入其中的所有内容都会丢失,您将在 objectAtIndex 中得到 nil .你做初始化 titarrylinkarray在你的viewDidLoad ,因此您正在从中获取数据。

关于 xml 的实际解析 - 我检查过您是否在可变字符串中获取了日期值 mutstrdate ,所以您的问题很可能与数组有关。

关于ios - NSXMLParser 的 nil 输出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24120841/

相关文章:

ios - 高度从 0 变为默认大小后单元格不显示

javascript - jPlayer 不会在 iOS 上播放第二次(有时)

ios - 将工具栏定位在屏幕顶部,底部有正确的阴影

python-pptx - 如何以编程方式访问演示文稿部分标题?

ios - 单例属性根据调用返回不同的值

objective-c - 如何在 cocoa touch/xcode 4 中为开发人员加密我的源代码和导出

ios - 关闭 UIImagePickerController 将 UITabBarController 重置为 0 索引 - iOS

xml - DTD 解析 : Parameter entity reference name including another parameter entity reference - is it well formed?

php - jQuery 将 XML 返回的字段名称大写?

ios - Collection Cell 未调用 RootViewController 中的函数(在代码应用程序中)