2012-12-04 9 views
0

나는 많은 블로그 응용 프로그램을 보유하고 있습니다. 최근에 그들 중 일부는 몇 가지 문제를 경험하기 시작했습니다. ASIHTTP 클래스와 GDataXML 클래스를 사용하여 WordPress 피드의 XML을 구문 분석하고 각 항목 (기사)을 가변 배열에 넣습니다. tableview는 각 기사의 셀에 모든 스토리를로드해야합니다. 내가 겪고있는 문제는 새 기사가 처음 실행될 때 표시되지 않고 사용자가 새로 고침을해야한다는 것입니다. 그러면 새 기사가 표시됩니다. 나는 지금 막 시험에 달렸다. 기사는 몇 시간 전에 게시되었습니다. 나는 앱을 돌렸다. 상쾌하게하기 위해 뽑아 냄으로써 나타났다. 앱을 완전히 종료하고 다시 시작하면 다시 사라졌습니다.TableView가 블로그의 모든 행을 표시하지 않음

@implementation RootViewController 


- (void)refresh { 
    self.allEntries = [NSMutableArray array]; 
    self.queue = [[[NSOperationQueue alloc] init] autorelease]; 
    self.feeds = [NSArray arrayWithObjects:@"http://bubblycandacebabbles.wordpress.com/?cat=-2008&feed=rss2", 
        nil]; 


    for (NSString *feed in _feeds) { 
     NSURL *url = [NSURL URLWithString:feed]; 
     ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url]; 
     [request setDelegate:self]; 
     [_queue addOperation:request]; 
    } 

} 

- (void)viewDidLoad { 
    [super viewDidLoad];  
    [activity startAnimating]; 
    //[self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbarcopy.png"] forBarMetrics:UIBarMetricsDefault]; 
    self.title = @"Blog"; 
     CGFloat nRed=111.0/255.0; 
    CGFloat nBlue=209/255.0; 
    CGFloat nGreen=229.0/255.0; 
    UIColor *myColor=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1]; 
    UIBarButtonItem *font = [[UIBarButtonItem alloc] initWithTitle:@"Change Font Size" style:UIBarButtonItemStylePlain target:self action:@selector(fontsizes)]; 
    self.navigationController.navigationItem.rightBarButtonItem = font; 
    self.tableView.backgroundColor = myColor; 

    self.refreshControl = [[UIRefreshControl alloc] init]; 

    [self.refreshControl addTarget:self action:@selector(refreshInvoked:forState:) forControlEvents:UIControlEventValueChanged]; 
    [self refresh]; 
} 
-(void) refreshInvoked:(id)sender forState:(UIControlState)state { 
    // Refresh table here... 
    [_allEntries removeAllObjects]; 
    [self.tableView reloadData]; 
    [self refresh]; 
} 

- (void)parseRss:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries { 

    NSArray *channels = [rootElement elementsForName:@"channel"]; 
    for (GDataXMLElement *channel in channels) {    

     NSString *blogTitle = [channel valueForChild:@"title"];      

     NSArray *items = [channel elementsForName:@"item"]; 
     for (GDataXMLElement *item in items) { 

      NSString *articleTitle = [item valueForChild:@"title"]; 
      NSString *articleUrl = [item valueForChild:@"link"];    
      NSString *articleDateString = [item valueForChild:@"pubDate"];   
      NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822]; 
      NSString *articleImage = [item valueForChild:@"content:encoded"]; 
      NSScanner *theScanner; 
      NSString *gt =nil; 
      theScanner = [NSScanner scannerWithString:articleImage]; 


      NSString *comments = [articleUrl stringByAppendingString:@"#respond"]; 
      NSString *commentslink = [NSString stringWithFormat: @"<a href=\"%@\">Leave A Comment</a>",comments]; 
      // find start of tag 
      [theScanner scanUpToString:@"alt=\"\" width=" intoString:NULL] ; 

      // find end of tag 
      [theScanner scanUpToString:@"/>" intoString:&gt] ; 
      // replace the found tag with a space 
      //(you can filter multi-spaces out later if you wish) 
      NSString *test = [articleImage stringByReplacingOccurrencesOfString:[ NSString stringWithFormat:@"%@", gt] withString:@"alt=\"\" width=\"150\" height=\"150\""]; 
      NSString *final = [test stringByReplacingOccurrencesOfString:@"float:none;height:30px" withString:@"float:none;height:1px"]; 
      NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
      [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
      [dateFormatter setDateStyle:NSDateFormatterShortStyle]; 
      NSString *dateofarticle = [dateFormatter stringFromDate:articleDate]; 
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
      NSString *smalltitle = [defaults objectForKey:@"Title"]; 
      NSString *smallbody = [defaults objectForKey:@"Article"]; 
      NSString *bodyoftext = [[[[[[[[[[[@"<head><body bgcolor=\"#6fd1e5\" text=\"#CC0099\"><style type='text/css'>a > img {pointer-events: none;cursor: default;max-width: 310;}</style></head><b><font size=" stringByAppendingString: smalltitle ] stringByAppendingString:@"><div align=\"left\"><FONT FACE=\"noteworthy\">" ]stringByAppendingString:articleTitle] stringByAppendingString:@"</font></b><font size=" ] stringByAppendingString:smallbody ] stringByAppendingString:@"><div align=\"left\"><FONT FACE=\"noteworthy\">"] stringByAppendingString:dateofarticle] stringByAppendingString:@"</div></p><FONT FACE=\"noteworthy\">"] stringByAppendingString:final] stringByAppendingString:commentslink]stringByAppendingString:@"</FONT>"]; 








      RSSEntry *entry = [[[RSSEntry alloc] initWithBlogTitle:blogTitle 
                 articleTitle:articleTitle 
                 articleUrl:articleUrl 
                 articleDate:articleDate 
                 articleImage:bodyoftext] autorelease]; 
      [entries addObject:entry]; 
     }  
    } 

} 


- (void)parseFeed:(GDataXMLElement *)rootElement entries:(NSMutableArray *)entries { 

    if ([rootElement.name compare:@"rss"] == NSOrderedSame) { 
     [self parseRss:rootElement entries:entries]; 
    } else if ([rootElement.name compare:@"feed"] == NSOrderedSame) {      
     [self parseAtom:rootElement entries:entries]; 
    } else { 
     NSLog(@"Unsupported root element: %@", rootElement.name); 
    }  
} 


// Customize the number of sections in the table view. 
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { 
    return 1; 
} 


// Customize the number of rows in the table view. 
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { 
    return [_allEntries count]; 
} 


// Customize the appearance of table view cells. 
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { 

    static NSString *CellIdentifier = @"Cell"; 

    Cell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 
    if (cell == nil) { 
     cell = [[Cell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier]; 
    } 



    RSSEntry *entry = [_allEntries objectAtIndex:indexPath.row]; 
    NSString *substring = @"http://bubblycandacebabbles.files.wordpress.com"; 
    NSRange textRange = [entry.articleImage rangeOfString:substring]; 

    if(textRange.location != NSNotFound){ 
     NSString *thearticleImage = entry.articleImage; 
     NSRegularExpression *expression = [NSRegularExpression regularExpressionWithPattern:@"src=\"([^\"]+)\"" options:NSRegularExpressionCaseInsensitive error:NULL]; 
     NSString *someString = thearticleImage; 
     NSString *oneurl = [someString substringWithRange:[expression rangeOfFirstMatchInString:someString options:NSMatchingCompleted range:NSMakeRange(0, [someString length])]]; 
     NSString *finalstring = [oneurl stringByReplacingOccurrencesOfString:@"src=\"" withString:@""]; 
     NSString *thefinalstring = [finalstring stringByReplacingOccurrencesOfString:@"\"" withString:@""]; 
     NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
     [dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; 
     [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
     [dateFormatter setDateStyle:NSDateFormatterShortStyle]; 
     CGFloat nRed=204.0/255.0; 
     CGFloat nBlue=0/255.0; 
     CGFloat nGreen=153.0/255.0; 
     UIColor *myColortext=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1]; 
     NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate]; 
     UIFont *cellFont = [UIFont fontWithName:@"noteworthy" size:16]; 
     UIFont *cellFont2 = [UIFont fontWithName:@"noteworthy" size:12];  
     CALayer * l = [cell.imageView layer]; 
     [l setMasksToBounds:YES]; 
     [l setCornerRadius:11]; 
     [l setBorderWidth:2.0]; 
     [l setBorderColor:[[UIColor blackColor] CGColor]]; 
     cell.textLabel.text = entry.articleTitle; 
     cell.textLabel.numberOfLines = 2; 
     cell.detailTextLabel.adjustsFontSizeToFitWidth = YES; 

     cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - Mother May I Blog", articleDateString]; 

     cell.textLabel.font = cellFont; 
     cell.detailTextLabel.font = cellFont2; 
     cell.textLabel.textColor = myColortext; 
     cell.detailTextLabel.textColor = myColortext; 
     [cell.imageView setImageWithURL:[NSURL URLWithString:thefinalstring] placeholderImage:[UIImage imageNamed:@"[email protected]"]]; 


    } 
    else { 
     CALayer * l = [cell.imageView layer]; 
     [l setMasksToBounds:YES]; 
     [l setCornerRadius:11]; 
     [l setBorderWidth:2.0]; 
     [l setBorderColor:[[UIColor blackColor] CGColor]]; 
     NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
     [dateFormatter setTimeZone:[NSTimeZone localTimeZone]]; 
     [dateFormatter setTimeStyle:NSDateFormatterShortStyle]; 
     [dateFormatter setDateStyle:NSDateFormatterShortStyle]; 
     NSString *articleDateString = [dateFormatter stringFromDate:entry.articleDate]; 
     UIFont *cellFont = [UIFont fontWithName:@"noteworthy" size:16];  
     UIFont *cellFont2 = [UIFont fontWithName:@"noteworthy" size:12];  
     cell.imageView.image = [UIImage imageNamed:@"[email protected]"]; 
     cell.textLabel.text = entry.articleTitle; 
     cell.textLabel.numberOfLines = 2; 
     cell.detailTextLabel.adjustsFontSizeToFitWidth = YES; 

     cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ - Mother May I Blog", articleDateString]; 
     CGFloat nRed=204.0/255.0; 
     CGFloat nBlue=0/255.0; 
     CGFloat nGreen=153.0/255.0; 
     UIColor *myColortext=[[UIColor alloc]initWithRed:nRed green:nBlue blue:nGreen alpha:1]; 
     cell.textLabel.font = cellFont; 
     cell.detailTextLabel.font = cellFont2; 
     cell.textLabel.textColor = myColortext; 
     cell.detailTextLabel.textColor = myColortext; 


    } 


    return cell; 
} 
+0

정말 트림해야합니다 당신이이 포럼에 대한 도움을 얻으려고한다면 코드를 게시하십시오. –

+0

@DanF 알았어, 내 질문의 본질을 다듬 었어. – user717452

답변

0

당신은 당신의 데이터가로드가 완료된 후 어느 시점에서

[self.tableView reloadData]; 

를 호출 할 필요가 : 여기에있는 TableView의 구현 코드입니다. 이 작업을 정확하게 수행하는 방법은 약간 까다 롭습니다. 작업 대기열이 비어있는 경우를 알려주는 방법이 필요합니다. 또는 이론적으로 대기열의 각 작업이 완료된 후이를 호출 할 수 있습니다. 그러면 테이블이 한 번에 하나씩 채워집니다. 이로 인해 사용자가 느린 연결을하는 경우 테이블을 다시로드하면 사용자 환경이 불안정해질 수 있고 다른 스레드의 reloadData을 호출하는 스레드 안전성에 긍정적이지 않습니다.

+0

처음 시작할 때조차도 reloadData를 호출해야하고 tableview가 비어 있습니까? – user717452

+0

데이터로드가 완료되면 셀을 새로 고칩니다. 테이블이 나타날 때 자동으로 한 번 호출되지만 수동으로 호출하지 않으면 다시 호출되지 않습니다. –

+0

그러면 사용자에게 모든 것을 한 번로드 한 다음 다시 수행하지 않겠습니까? – user717452

관련 문제