简体   繁体   English

仅将某些项目从XML添加到TableView

[英]Add only SOME items from XML to TableView

Using this tutorial , I made an iPhone blog app. 使用本教程 ,我制作了一个iPhone博客应用程序。 It uses the count of the array created to setup the number of rows. 它使用创建的数组的计数来设置行数。 I don't want to do every single item, because there are over 200 right now and growing. 我不想做每一个项目,因为现在有200多个并且还在增长。 When I return any number for rows in section, it always crashes with the error about 0 beyond bounds of empty array. 当我为节中的行返回任何数字时,它总是崩溃并显示错误,错误超出空数组的范围,为0左右。 What else do I need to tweak from this tutorial to only allow the first 20 items to show in tableview? 我还需要从本教程中进行哪些调整,以仅允许前20个项目显示在表格视图中?

UPDATE: I think I am making some progress. 更新:我想我正在取得一些进展。 In the reqeustFinished method where it sorts the array, I edited it to make it this: 在对数组进行排序的reqeustFinished方法中,我对其进行了编辑以使其变为:

NSMutableArray *entries = [NSMutableArray array];
            [self parseFeed:doc.rootElement entries:entries];                
            [entries removeLastObject];

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                for (RSSEntry *entry in entries) {
                    int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
                        RSSEntry *entry1 = (RSSEntry *) a;
                        RSSEntry *entry2 = (RSSEntry *) b;
                        return [entry1.articleDate compare:entry2.articleDate];
                    }];
                    NSLog(@"%@", entries);

                    [_allEntries insertObject:entry atIndex:insertIdx];
                    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
                                          withRowAnimation:UITableViewRowAnimationRight];

Adding the line to removeLastObject for entries, removed the first item (which is ideally the ONLY one I would want on the first day). 在条目的removeLastObject中添加一行,以删除第一项(理想情况下,这是我第一天想要的唯一项)。 Are there other methods that would allow me to remove a range of objects at Index? 还有其他方法可以让我删除Index上的一系列对象吗?

Here is the code I have for the Table View Class and DataSources. 这是表视图类和数据源的代码。

- (void)refresh {
    self.allEntries = [NSMutableArray array];
    self.queue = [[[NSOperationQueue alloc] init] autorelease];
    self.feeds = [NSArray arrayWithObjects:@"addressofxmlfile",
                  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];    
    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:@"guid"];            
            NSString *articleDateString = [item valueForChild:@"pubdate"];        
            NSDate *articleDate = [NSDate dateFromInternetDateTimeString:articleDateString formatHint:DateFormatHintRFC822];
            NSString *articleImage = [item valueForChild:@"description"];
            NSDateFormatter * dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
            [dateFormatter setTimeStyle:NSDateFormatterShortStyle];
            [dateFormatter setDateStyle:NSDateFormatterMediumStyle];
            NSString *dateofarticle = [dateFormatter stringFromDate:articleDate];
            NSString *days = [articleImage substringFromIndex:7];


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

        }      
    }

}


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

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

- (void)requestFinished:(ASIHTTPRequest *)request {

    [_queue addOperationWithBlock:^{

        NSError *error;
        GDataXMLDocument *doc = [[GDataXMLDocument alloc] initWithData:[request responseData] 
                                                               options:0 error:&error];
        if (doc == nil) { 
            NSLog(@"Failed to parse %@", request.url);
        } else {

            NSMutableArray *entries = [NSMutableArray array];
            [self parseFeed:doc.rootElement entries:entries];                

            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                for (RSSEntry *entry in entries) {

                    int insertIdx = [_allEntries indexForInsertingObject:entry sortedUsingBlock:^(id a, id b) {
                        RSSEntry *entry1 = (RSSEntry *) a;
                        RSSEntry *entry2 = (RSSEntry *) b;
                        return [entry1.articleDate compare:entry2.articleDate];
                    }];

                    [_allEntries insertObject:entry atIndex:insertIdx];
                    [self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:[NSIndexPath indexPathForRow:insertIdx inSection:0]]
                                          withRowAnimation:UITableViewRowAnimationRight];

                }                            

            }];

        }        
    }];
    [self.refreshControl endRefreshing];

}

- (void)requestFailed:(ASIHTTPRequest *)request {
    NSError *error = [request error];
    NSLog(@"Error: %@", error);
    [self refresh];
}

#pragma mark -
#pragma mark Table view data source

// Customize the number of sections in the table view.
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  // [tableView setBackgroundColor:[UIColor redColor]];
    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];


           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:@"Papyrus" size:19];
        UIFont *cellFont2 = [UIFont fontWithName:@"Papyrus" size:17];
       // cell.imageView.image = [UIImage imageNamed:@"icon@2x.png"];
        cell.textLabel.text = entry.date;
        cell.detailTextLabel.text = entry.articleTitle;
    cell.detailTextLabel.textColor = [UIColor blackColor];

        cell.textLabel.font = cellFont;
        cell.detailTextLabel.font = cellFont2;





    return cell;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

    return 73.4;


}

You are assigning allEntries to new Array in the Refresh method here: 您将在此处的Refresh方法中将allEntries分配给新的Array:

- (void)refresh {
    self.allEntries = [NSMutableArray array];

The tutorial only does this in the ViewDidLoad Method. 本教程仅在ViewDidLoad方法中执行此操作。 Not sure if this is a problem as i don't know exactly when/how refresh is called. 不知道这是否是一个问题,因为我不知道何时/如何调用刷新。

Found this answer that shows how to hide cells/rows here . 找到此答案,该答案显示了如何在此处隐藏单元格/行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM