我有一个存储一些数据的表。假设数据太大,无法一次全部加载到内存中。我想在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一对一地获取它们吗?
最佳答案
根据docs,您需要初始化获取请求,并且您可能还想根据滚动进度来设置获取偏移量。但是您必须手动跟踪它。这是一个可以实现它的基本方法。
PS。我尚未测试此代码。我只是在文本编辑器中写的:)。但它应该可以按照您的要求工作。例如,装载限制为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;
}
希望对您有所帮助:)
关于ios - UItableView与MagicalRecord的巨大数据集,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33527262/