NSXMLParser的nil输出问题

时间:2014-06-09 12:58:35

标签: ios objective-c xml nsxmlparser null

我正在使用NSXMLParser从我的博客解析和RSS2提要,以在表格视图中输入数据。在我的下面的代码中,我遇到了接收" nil"对于pubDate和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 个答案:

答案 0 :(得分:1)

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

  1. 结束部分xml(</content:encoded></item>
  2. 数组变量的初始化:datearray, descarray
  3. 如果您也没有在实际代码中初始化数组,那么您尝试放入其中的所有内容都将丢失,并且您将在objectAtIndex中获得nil。您在titarry中初始化了linkarrayviewDidLoad,因此您可以从中获取数据。

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