我工作的地方是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.這是標準類先有大寫字母。有助於可讀性 –