带有MagicalRecord巨大数据集的UItableView

我有一个表存储一些数据。 假设数据太大,无法一次加载到内存中。 我想在UItableView中显示这些数据。

-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView { return 1; } -(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [Item MR_numberOfEntities]; } -(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath]; // How to get object for this row ??? return cell; } 

我知道的唯一方法是将所有数据加载到数组中

 NSArray *items = [Item MR_findAll]; 

但我不想这样做。 用户将显示前10行,为什么我应该从CoreData加载它们。 有什么办法使用MagicalRecord一个接一个地取出它们吗?

根据文档你需要初始化获取请求,你也可能想设置取决于滚动进度的偏移量..但你将不得不手动跟踪它。 这是一个如何实现的基本方法。 PS。 我没有testing过这个代码。 我只是写在文本编辑器:)。 但它应该按照你的要求工作。 例如装载限制10的项目。

  @property (nonatomic) int itemCount; @property (nonatomic, strong) NSMutableArray * items static const int FETCH_LIMIT = 10; -(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return _itemCount; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { // Classic start method static NSString *cellIdentifier = @"MyCell"; MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainMenuCellIdentifier]; } MyData *data = [self.itemsArray objectAtIndex:indexPath.row]; // Do your cell customisation // cell.titleLabel.text = data.title; if (indexPath.row == _itemCount - 1) { [self loadMoreItems]; } } -(void)loadMoreItems{ int newOffset = _itemCount+FETCH_LIMIT; // Or _itemCount+FETCH_LIMIT+1 not tested yet NSArray * newItems = [self requestWithOffset: newOffset]; if(!newItems || newItems.count == 0){ // Return nothing since All items have been fetched return; } [ _items addObjectsFromArray:newItems ]; // Updating Item Count _itemCount = _items.count; // Updating TableView [tableView reloadData]; } -(void)viewDidLoad{ [super viewDidLoad]; _items = [self requestWithOffset: 0]; _itemCount = items.count; } -(NSArray*)requestWithOffset: (int)offset{ NSFetchRequest *itemRequest = [Item MR_requestAll]; [itemRequest setFetchLimit:FETCH_LIMIT] [itemRequest setFetchOffset: offset] NSArray *items = [Item MR_executeFetchRequest:itemRequest]; return items; } 

希望你觉得有帮助:)