2015-11-04 3 views
0

У меня есть таблица, в которой хранятся некоторые данные. Предположим, что данные слишком велики для загрузки в память сразу. Я хочу показать эти данные в UItableView.UItableView с огромным набором данных MagicalRecord

-(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?

+0

Этого ответа старого (и MagicalRecord измененных много с тех пор), но вы можете поставить fetchLimit с пользовательской выборкой: https://github.com/magicalpanda/MagicalRecord/issues/283 – Larme

+0

@Yegor Razumovsky Обновлен мой ответ в соответствии с вашими требованиями! – ProblemSlover

+0

Если вы не можете использовать 'NSFetchedResultsController' с MR, я предлагаю сбросить MR. – Avi

ответ

1

В соответствии с 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; 
    } 

Надеются, что вы найдете ее полезным :)

Смежные вопросы