我保存了我的coredata,现在我正在尝试在tableview类中获取它。当我点击一个按钮时,标签会被保存到核心数据中。当我尝试取出它时,我的细胞上没有任何显示。我知道我必须在cellForRowAtIndexPath方法中做点什么..请原谅我如果我的代码不好我就是菜鸟。
.m文件,带有保存核心数据的操作按钮
- (IBAction)AddFavorite:(UIButton *)sender {
AppDelegate *appDelegate1 = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate1 managedObjectContext];
NSManagedObjectContext *gameSelection;
gameSelection = [NSEntityDescription insertNewObjectForEntityForName:@"GamesDatabase" inManagedObjectContext:context];
[gameSelection setValue: _labelGame.text forKey:@"game"];
_labelGame.text = @"";
NSError *error;
[context save:&error];
_confirmAdd.text = @"Add Game!";
}
.m要获取的tableview类
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
//view did load is called when your view is actually presented onscreen
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
//this is a table view datasource method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 2;
}
//table view data source method(required)
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
if (section == 0){
return 10;
}
if (section == 1){
return 15;
}
}
//table view data source method
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
if (section==0) {
return @"Top Ten";
} else if (section==1) {
return @"Other Favorites";
}
return nil;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
//set the managed object context
AppDelegate *appDelegate1 = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate1 managedObjectContext];
//establish the entity we want to search
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:@"GamesDatabase" inManagedObjectContext:context];
//establishing a fetch request and a place for us to write the found data
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
//setting our search criteria by name
NSPredicate *pred1 = [NSPredicate predicateWithFormat:@"(game = %@)",cell.textLabel.text];
[request setPredicate:pred1];
//"runs" the query
NSError *error;
NSArray *objects = [context executeFetchRequest:request error:&error];
// Configure the cell...
if(cell == nil) {
cell.textLabel.text = [NSString stringWithFormat:@"%@",[objects objectAtIndex:indexPath.row]];
}
return cell;
[tableView reloadData];
}