TableView没有显示CoreData的数据

时间:2013-10-10 22:23:33

标签: core-data uitableview segue

我在项目中工作,其中TableViewController是初始控制器。然后我有CoreData存储我的数据。从我的第一个TableViewController我通过storyboard中的push segue到达ViewController。在那个ViewController中,我将数据添加到我的Core数据中,但是当ViewController关闭并且TableViewController返回时,我的表仍然是空的。

这是我的表格代码:

- (void)viewDidLoad
{

[super viewDidLoad];
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
_managedObjectContext = [appDelegate managedObjectContext];

NSFetchRequest*request = [[NSFetchRequest alloc]init];
NSEntityDescription*name = [NSEntityDescription entityForName:@"nameEntity" inManagedObjectContext:_managedObjectContext];
[request setEntity:name];

NSError*error = nil;
NSMutableArray*mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error]mutableCopy];
if (mutableFetchResults == nil) {

}
 [self setMutableArray:mutableFetchResults];
[self.tableView reloadData];
}

比我的表行代码:

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
} 

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return mutableArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Name";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
Name*name = (Name*) [mutableArray objectAtIndex:indexPath.row ];

cell.textLabel.text = name.shop;
cell.detailTextLabel.text = name.date;
return cell;
}

这里的代码我在ViewController中存储了这些数据:

- (IBAction)addData:(id)sender;{
Name *name = [NSEntityDescription     insertNewObjectForEntityForName:@"nameEntity"   inManagedObjectContext:_managedObjectContext];
[name setShop:textField.text];
NSDate*date = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd.MM.yyyy"];
NSString *dateString = [df stringFromDate:date];
[zoznam setDate:dateString];

1 个答案:

答案 0 :(得分:0)

您正在致电

[self.tableView reloadData];
在您的viewDidLoad中的

,当您关闭viewController时不会调用它。如果您想重新加载dataSource,请尝试以下方法:

- (void)viewWillAppear:(BOOL)animated{
     AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
      _managedObjectContext = [appDelegate managedObjectContext];

      NSFetchRequest*request = [[NSFetchRequest alloc]init];
      NSEntityDescription*name = [NSEntityDescription entityForName:@"nameEntity"  inManagedObjectContext:_managedObjectContext];
      [request setEntity:name];

      NSError*error = nil;
      NSMutableArray*mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error]mutableCopy];
      [self setMutableArray:mutableFetchResults];
     [self.tableView reloadData];
 }