IOS核心数据,UITableView加载更多数据



在我的IOS项目中,我使用核心数据。我有1000个元素首先,我需要在UITableView中显示30个元素。当用户滚动并到达UITableView的底部(末尾有5个元素)时,我可以将新数据加载到表中。我该怎么做

我使用了这个代码,但它没有按照我想要的工作

#import "HomeViewController.h"
#import "GDMnLineRKObjectManager.h"
#import "CoreData+MagicalRecord.h"
#import "CinNames.h"
#import "Event.h"
@interface HomeViewController ()<UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property NSUInteger dpc;
@property BOOL is_load;
@property BOOL process_loading;
@property NSFetchRequest *fetchRequest;
@property (nonatomic) BOOL loadingMoreTableViewData;
@property (nonatomic) NSUInteger  inf_counter;
@end
@implementation HomeViewController
//@synthesize tableView;
- (IBAction)showMenu
{
    // Dismiss keyboard (optional)
    //
    [self.view endEditing:YES];
    [self.frostedViewController.view endEditing:YES];
    // Present the view controller
    //
    [self.frostedViewController presentMenuViewController];
    [self.tableView reloadData];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)saveToStore
{
    // Saving to persistent store for further usage.
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.dpc = 0;
    self.inf_counter = self.dpc;
    self.is_load = NO;
    self.process_loading = NO;
    self.fetchRequest = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([Event class])];
    // Do any additional setup after loading the view, typically from a nib.
    /*
     */
    [self loadElements];
    ////
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    ///
}

- (void)loadElements
{
    // Get an array of remote "character" objects. Specify the offset.
    [[GDMnLineRKObjectManager manager] getMnLineObjectsAtPath:SERVER_PATH_LOAD
                                                   parameters:@{@"someval" : @("564")}
                                                      success:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
                                                      }
                                                      failure:^(RKObjectRequestOperation *operation, NSError *error) {
                                                          // Failed to load characters.
                                                          /*
                                                           [self animateActivityIndicator:NO];
                                                           [bottomPullView finishedLoading];
                                                           */
                                                          [[[UIAlertView alloc] initWithTitle:@"Marvel API Error" message:operation.error.localizedDescription delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Retry", nil] show];
                                                      }];
}

#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultsController sections][section];
    return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"III = %@", indexPath);
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"HuCell" forIndexPath:indexPath];
    [self configureCell:cell atIndexPath:indexPath];
     if (indexPath.row > self.inf_counter - 5) {
     // User has scrolled to the bottom of the list of available data so simulate loading some more if we aren't already
         if (!self.loadingMoreTableViewData && self.process_loading == NO) {
             self.loadingMoreTableViewData = YES;
             self.process_loading = YES;
             [self performSelector:@selector(addSomeMoreEntriesToTableView) withObject:nil afterDelay:0.0f];
         }
     }
     if (indexPath.row < self.inf_counter) {
         [self configureCell:cell atIndexPath:indexPath];
     } else {
         cell.textLabel.text = @"Loading more data...";
     }
    return cell;
}

- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
    NSManagedObject *object = [self.fetchedResultsController objectAtIndexPath:indexPath];
    NSString * string3 = [NSString stringWithFormat:@"%@ - %ld", [[object valueForKey:@"name"] description], (long)indexPath.row];
    cell.textLabel.text =  string3;//[[object valueForKey:@"name"] description];
}

#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
    NSLog(@"Skolko");
    if ((!_fetchedResultsController || self.process_loading == YES))  {
        self.process_loading = NO;
        self.is_load = NO;
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"timeStamp" ascending:NO];
        self.fetchRequest.sortDescriptors = @[sortDescriptor];
        self.fetchRequest.fetchLimit = self.dpc;
        //self.fetchRequest.fetchBatchSize = 30;
        self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:self.fetchRequest managedObjectContext:[RKManagedObjectStore defaultStore].mainQueueManagedObjectContext sectionNameKeyPath:nil cacheName:nil];
        self.fetchedResultsController.delegate = self;
        NSError *error;
        [self.fetchedResultsController performFetch:&error];
        NSLog(@"%@",[self.fetchedResultsController fetchedObjects]);
        NSLog(@"Counta: %lu",(unsigned long)[self.fetchedResultsController.fetchedObjects count]);
        NSAssert(!error, @"Error performing fetch request: %@", error);
        self.inf_counter = [self.fetchedResultsController.fetchedObjects count];
        [self.tableView reloadData];
    }
    return _fetchedResultsController;
}
- (void)addSomeMoreEntriesToTableView {
    self.dpc += 20;
    [self fetchedResultsController];
    self.loadingMoreTableViewData = NO;
    [self.tableView reloadData];
}
- (void)scrollViewDidScroll: (UIScrollView*)scroll {
     // UITableView only moves in one direction, y axis
     CGFloat currentOffset = scroll.contentOffset.y;
     CGFloat maximumOffset = scroll.contentSize.height - scroll.frame.size.height;
     NSLog(@"hui = %f", (maximumOffset - currentOffset));
     // Change 10.0 to adjust the distance from bottom
     if (maximumOffset - currentOffset <= 10.0) {
         self.is_load = YES;
         self.dpc += 10;
         [self fetchedResultsController];
         //[self.tableView reloadData];
     }

}
@end

您要查找的是NSFetchRequest上的fetchBatchSize属性。我希望您也在使用NSFetchedResultsController,它与表视图和集合视图配合得非常好。以下是描述:

使用提取的结果控制器可以有效地管理结果从核心数据获取请求返回,为UITableView对象。

因此,在设置提取结果控制器之前,只需确保设置提取请求的fetchBatchSize,并让框架为您处理所有优化。

编辑

OP希望最初的提取只包括30个项目,然后只有当用户滚动时,它才应该重新填充提取。在大多数情况下,fetchBatchSize应该是解决方案,因为核心数据会试图对所有结果进行容错,从而避免获取所有对象的开销,而更倾向于延迟地对它们进行容错。为了坚持OP,解决方案可能是这样的:

- (NSFetchRequest *)createFetchRequest {
    NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:NSStringFromClass([MyEntity class])];
    fetch.predicate = //set up your fetch
    return fetch;
}

然后,当你实例化你的控制器时,你可以设置提取限制:

NSFetchRequest *fetchRequest = [self createFetchRequest];
fetchRequest.fetchLimit = 30;
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                             managedObjectContext:context
                                                                               sectionNameKeyPath:nil cacheName:nil];
self.controller = controller;

由于控制器上的fetchRequest属性是readOnly,当您想要获取所有内容时,您必须重新分配控制器:

NSFetchRequest *fetchRequest = [self createFetchRequest];
NSFetchedResultsController *controller = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                                                                 managedObjectContext:context
                                                                                   sectionNameKeyPath:nil cacheName:nil];
[controller performFetch:nil];
self.controller = controller;

如果你想继续更多,请访问Ray Wenderlich,他们为iOS提供了很棒的教程。

快乐编码

选项:

观看WWDC 2011的高级滚动查看技术。

教程:http://mobiledevelopertips.com/user-interface/creating-circular-and-infinite-uiscrollviews.html

最新更新