【问题标题】:How to show the data of Core Data in a UITableView如何在 UITableView 中显示 Core Data 的数据
【发布时间】:2014-09-16 07:01:14
【问题描述】:

我从 JSON 获取响应并使用 Core Data 存储该数据。我想始终在UITableView 中显示数据。你能建议我如何在UITableView 中显示数据吗?

这是我正在使用的代码。

    NSManagedObject * newEntry =[[NSManagedObject alloc]initWithEntity:entityDesc insertIntoManagedObjectContext:self.managedObjectContext];

    [newEntry setValue:[dict objectForKey:@"albumName"] forKey:@"albumName"];
    [newEntry setValue:[dict objectForKey:@"coverPhotoURL"] forKey:@"coverPhotoURL"];
    [newEntry setValue:[dict objectForKey:@"createdDate"] forKey:@"createdDate"];

    NSLog(@"Log %@", newEntry);

    NSError * error = nil;
    if ([self.managedObjectContext save:&error] == NO)
    {
        NSLog(@"CANNOT SAVE: %@ %@", error, [error localizedDescription]);
    }
    else {
        NSLog(@"SUCCES, go check the sqlite file");
    }
}


NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];    
NSEntityDescription *entity = [NSEntityDescription entityForName:@"GetAlbums"
                                          inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];

NSError* error;    
NSArray *fetchedRecords = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
NSLog(@"Fetch Records %@",fetchedRecords);

【问题讨论】:

  • 你知道UITableViewControllers怎么用吗?
  • 你知道tableView
  • 您已经有了获取的记录数组,然后在表格视图中显示它们。 - 你的问题是关于如何从数组中提取元素?
  • 我只写了这个 [self.tableView reloadData];

标签: ios objective-c uitableview core-data


【解决方案1】:

即使按照walle84 的建议,您可以实现UITableViewDelegate 的方法在表格视图中显示数据,正确的方法是使用UITableViewNSFetchedResultsController。正如文档中所写,后者是使用的

有效地管理从 Core Data 获取请求返回的结果,以便为 UITableView 对象提供数据。

我把重点放在高效上,因为它提供了很多优点。例如,它允许延迟加载数据,它允许跟踪特定实体的更改(实现NSFetchedResultsControllerDelegate)等等。

从哪里开始?有很多啧啧。只需用谷歌搜索它们,您就会找到一个很好的起点。

【讨论】:

    【解决方案2】:

    您使用以下表格视图方法来显示您的数据。

    -(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
        return  [self.arrayOfyourData count];
    }
    
    -(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
        return 1;
    }
    
    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        static NSString *cellIdentifier = @"CellIdentifier";
    
        //you could use default cell or ur own custom cell.
        cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
        // Now here you could pare your self.arrayOfyourData to fetch and populate your cell.
    
        return cell;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-12-11
      • 2021-01-16
      • 2012-11-30
      • 2012-08-27
      • 2013-07-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多