【问题标题】:IOS/Objective-C: can't display core data informationIOS/Objective-C:无法显示核心数据信息
【发布时间】:2017-02-10 21:39:44
【问题描述】:

我的应用遵循 web(json)->appDelegate (Core Data)->ViewController 的方案。到目前为止,我可以看到从序列化 json 获得的位置以及我输入用于测试的所有其他新位置。但现在我试图在表格视图中显示它们,但到目前为止它不起作用。尽管我知道这些位置在核心数据中,但该表仍然是空的:代码如下:

#import "TableTableViewController.h"
#import "DetailViewController.h"
#import <CoreData/CoreData.h>
#import "Spot.h"
#import "AppDelegate.h"




@interface TableViewController ()

@property (strong) NSMutableArray *locations;

@end

@implementation TableViewController

- (NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate respondsToSelector:@selector(managedObjectContext)]){
        context = [delegate managedObjectContext];
    }
    return context;
}


- (void)viewDidLoad {
    [super viewDidLoad];

    NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Spot"];
    self.locations = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];

    [self.tableView reloadData];

    }

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {


    return self.locations.count;

}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

    NSManagedObject *ls = [self.locations objectAtIndex:indexPath.row];
    [cell.textLabel setText:[NSString stringWithFormat:@"%@", [ls valueForKey:@"name"]]];


    return cell;
}

谁能告诉我我做错了什么?

更新: 如果我记录位置-> NSLog(@"%@ 位置是", _locations);我得到一个空结果。这意味着获取的数据没有填充数组,因此表保持为空,对吗?但是为什么没有填充数组呢?

【问题讨论】:

  • 我需要检查我的数据库是否为空?我该怎么做?
  • 为了进行健全性检查,我会在 numberOfRowsInSection 方法中设置一个断点,以确保它被调用,然后,如果它被命中,打印出 self.locations.count 的结果并确保它不是 0。如果断点跳闸并且计数大于 0,那么您有数据。
  • 您尝试过@conarch 的建议吗?
  • 如何实施该建议?我对此有点陌生;这是我的第一个应用程序...
  • 更新:如果我记录位置,像这样 [self.tableView reloadData]; NSLog(@"%@ 里斯本", _llocations);我得到一个空结果。这意味着数组没有接收到获取的数据,对吧?但为什么呢?

标签: ios objective-c uitableview core-data


【解决方案1】:

检查您的 self.tableView.dataSource 是否为 nil

【讨论】:

  • 对不起,我不明白
  • - (void)viewDidLoad { [super viewDidLoad]; self.tableView.dataSource = self;//添加这个
猜你喜欢
  • 1970-01-01
  • 2015-07-13
  • 2015-03-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-30
相关资源
最近更新 更多