简体   繁体   中英

Add only SOME items from XML to TableView

Using this tutorial , I made an iPhone blog app. 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. When I return any number for rows in section, it always crashes with the error about 0 beyond bounds of empty array. What else do I need to tweak from this tutorial to only allow the first 20 items to show in tableview?

UPDATE: I think I am making some progress. In the reqeustFinished method where it sorts the array, I edited it to make it this:

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). Are there other methods that would allow me to remove a range of objects at 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:

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

The tutorial only does this in the ViewDidLoad Method. 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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