NSXMLParser의 nil 출력 문제

SuperAdmin

NSXMLParser를 사용하여 내 블로그에서 RSS2 피드를 구문 분석하고 테이블보기에 데이터를 입력하고 있습니다. 아래 코드에서 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];


}
Andris Zalitis

제시 한 코드에서 두 가지가 누락되었습니다.

  1. XML의 끝 부분 ( </content:encoded></item>)
  2. 배열 변수 초기화 : datearray, descarray

실제 코드에서도 배열을 초기화하지 않으면 배열에 넣으려고 한 모든 것이 손실되고 objectAtIndex. 초기화를 수행 titarry하고 linkarray에서 viewDidLoad데이터를 가져옵니다.

xml의 ​​실제 구문 분석과 관련하여 변경 가능한 문자열에서 날짜 값을 얻었는지 확인 mutstrdate했기 때문에 문제가 배열과 관련이있을 가능성이 큽니다.

이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.

침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제

에서 수정
0

몇 마디 만하겠습니다

0리뷰
로그인참여 후 검토

관련 기사

분류에서Dev

c의 출력 문제

분류에서Dev

dev C ++의 출력 문제

분류에서Dev

북 다운의 PDF 출력 문제

분류에서Dev

.CSV 파일의 출력 문제

분류에서Dev

Java 형식의 출력 문제

분류에서Dev

PowerShell의 파일 출력 문제

분류에서Dev

awk 출력의 제어 문자

분류에서Dev

간단한 퀴즈의 출력 문제

분류에서Dev

Nest API의 출력 JSON 문제

분류에서Dev

매크로의 출력 문제?

분류에서Dev

Powershell 기능의 출력 문제

분류에서Dev

해시의 출력 형식 문제

분류에서Dev

proc_open ()의 출력 문제

분류에서Dev

파이썬의 목록 이해력 출력 문제

분류에서Dev

Pandas to_sql ()을 호출 할 때 SQL 문의 출력 억제

분류에서Dev

펄 코드의 MQ 출력 문제에서 데이터 추출

분류에서Dev

양식 CSS 문제의 입력 유형 제출 버튼

분류에서Dev

PHP XML 출력의 문자 인코딩 문제

분류에서Dev

Powershell의 복제 출력

분류에서Dev

지도의 주문 출력

분류에서Dev

C의 문자열 입력 / 출력

분류에서Dev

slidy 출력이있는 Rmarkdown의 slide_level 문제

분류에서Dev

Google Colab의 pydatatable 프레임 출력 문제

분류에서Dev

for 루프의 출력에 문제가 있습니까?

분류에서Dev

출력 레이어의 소프트 맥스 기능 문제

분류에서Dev

PyTorch의 다중 출력 회귀 문제에 대한 RMSE 손실

분류에서Dev

openCV의 imshow로 DFT 출력 표시 문제

분류에서Dev

출력을 C ++의 주 함수에 넣는 문제

분류에서Dev

len과 출력의 문제점은 무엇입니까