使用核心数据向表视图添加节

时间:2013-08-08 21:24:23

标签: ios uitableview core-data

在我的应用程序中,用户使用coreData将单元格添加到tableView。这非常有效。但现在我希望表视图有部分。

添加新单元格的viewController如下所示:

@property (strong) NSManagedObject *travel;
    ...
-(void)viewDidLoad{
            countryName = [[NSArray alloc] initWithObjects:
                             @"USA", @"England", @"Italy", nil];
    countryLabel.text= [countryName objectAtIndex:[picker selectedRowInComponent:0]];

  } 
    - (IBAction)save:(id)sender {

            [self.travel setValue:countryLabel.text forKey:@"country"];
}

并在viewController中显示tableView中的单元格:

       @property (strong) NSMutableArray *travelAll;
  ...
         NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
            NSPredicate *predicate=[NSPredicate predicateWithFormat:@"position == %@",_positionString];
            NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"Travel"];
            [fetchRequest setPredicate : predicate ];
            self.travelAll = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];  

        [self.tableView reloadData];

        ...

        - (NSString *)tableView:(UITableView *)tableView
        titleForHeaderInSection:(NSInteger)section
        {    NSArray* headers = [NSArray arrayWithObjects:@"USA",@"England","Italy",nil];

            return [headers objectAtIndex:section];
        }


        - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
        {
            // Return the number of sections.
            return 3;
        }

        - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
        {
            return [self.travelAll count];
        }

            - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
        {
            static NSString *CellIdentifier = @"Cell";
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

            NSManagedObject *travel = [self.travelAll objectAtIndex:indexPath.row];
        ...
        return cell;
        }

但是现在我的tableView我只有这三个部分(标题),但我无法添加单元格。 例如:用户为其新单元格选择 USA ,因此该单元格应显示在 USA

部分中

1 个答案:

答案 0 :(得分:0)

您的数据源方法存在缺陷。例如,您为每个部分返回相同的单元格数据。还有其他问题。

使用NSFetchedResultsController要好得多。从Apple模板开始(如果您创建一个新项目并选择“使用核心数据”,则可以使用该模板),这些模板使用获取的结果控制器。

您的部分设计变得非常简单:只需指定sectionNameKeyPath属性即可。

相关问题