我工作的地方是TableViewController作为初始控制器。然后我有我的数据存储CoreData。从我的第一个TableViewController中,我通过storyboard中的push segue来到ViewController。在那个ViewController中,我将数据添加到我的Core数据中,但是当ViewController关闭并且TableViewController返回时,我的表仍然是空的。TableView没有显示来自CoreData的数据
这里是我的表码:
- (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];
只是一个小技巧,你的“名字”类应该有一个大写N.这是标准类先有大写字母。有助于可读性 –