2014-06-09 5 views
0

NSXMLParser를 사용하여 내 블로그에서 RSS2 피드를 구문 분석하고 테이블 뷰에 데이터를 입력하고 있습니다. 아래 코드에서 pubDate에 "nil"을, XML의 설명 태그를받는 데 문제가 있습니다. 아래 XML과 코드, 그리고 내 ViewController입니다.NSXMLParser에서 nil 출력 문제.

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 *[email protected]"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

당신은 당신이 두 가지를 놓치고 제시 한 코드에서 :

    을배열 변수의 ( </content:encoded></item>)
  1. 초기화하여 XML의 일부를 종료
  2. : 당신이 너무 실제 코드에서 배열을 초기화하지 않으면 datearray, descarray

은 모든 당신이 그들에 넣어 노력은, 손실 , 당신은 objectAtIndex에 nil을 갖게 될 것입니다. viewDidLoadtitarrylinkarray을 초기화하므로 데이터를 가져 오는 중입니다.

xml의 실제 파싱에 관해서는 변경 가능한 문자열 mutstrdate에서 날짜 값을 확인 했으므로 문제는 배열과 관련이 있습니다.