有关获取核心数据的一些问题

时间:2016-04-01 09:04:35

标签: ios uitableview core-data

我是iOS的新人,我制作了一个APP并使用了Core Data。我可以在Entity中保存数据,但是我无法获取它。它会担心语法或其他原因。

我想获取数据并在TableViewCell中显示

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:SectionsTableIdentifier];

    NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:@"Entity"];
    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"showName" ascending:NO];
    request.sortDescriptors = @[sort];

    request.fetchLimit = 100;
    request.fetchOffset= 0;

    NSError *error = nil;
    NSArray *array = [self.context executeFetchRequest:request error:&error];
    NSMutableDictionary *names = [NSMutableDictionary dictionaryWithCapacity:1];
    if(!error){
        for (Entity *emp in array ) {
            NSLog(@"output:%@",emp.showName);
            names =[NSMutableDictionary dictionaryWithObjectsAndKeys:emp.showName, nil];
            self.keys =[[self.names allKeys]sortedArrayUsingSelector:@selector(compare:)];
        }
    }
    else{
        NSLog(@"%@",error);
    }

}

这是我保存数据的代码

-(IBAction)addButton:(id)sender{
    AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;

    NSManagedObjectContext *context = [appDelegate managedObjectContext];


    NSInteger seasonRow = [self.dataPicker selectedRowInComponent:kSeason];
    NSInteger episodeRow = [self.dataPicker selectedRowInComponent:kEpisode];
    Entity * tvShow1 =[NSEntityDescription insertNewObjectForEntityForName:@"Entity"
                                                    inManagedObjectContext:context];
    NSError * error = nil;

    NSString *name = self.nameField.text;
    NSString *introduction = self.introductionField.text;
    NSString *dateSeason = self.seasonNumber[seasonRow];
    NSString *dateEposide = self.episodeNumber[episodeRow];
    NSString *date;
    date = [dateSeason stringByAppendingString:dateEposide];
    tvShow1.showName =name;
    tvShow1.showIntroduction = introduction;
    tvShow1.showLastedData = date;
    if (!error) {
        NSLog(@"保存成功");
        NSString *message = [[NSString alloc]initWithFormat:@"你的新剧:%@已经成功添加",name];
        UIAlertController *alert=
        [UIAlertController alertControllerWithTitle:@"恭喜,添加成功"
                                            message:message
                                     preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"好嘞!"
                                                         style:UIAlertActionStyleDefault
                                                       handler:nil];
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];
        [self.contenxt save:&error];
    }
    [appDelegate saveContext];
}

非常感谢!

0 个答案:

没有答案