【问题标题】:Adding sections to tableView using coreData使用 coreData 将部分添加到 tableView
【发布时间】:2013-08-08 21:24:22
【问题描述】:

在我的应用程序中,用户使用 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"];
}

以及在 tableView 中显示单元格的 viewController 中:

       @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

部分

【问题讨论】:

  • 您的单元格标识符是否已在情节提要中设置?
  • @AbdullahShafique 是的
  • 单元格 id 是“单元格”吗? (只是确保)
  • @AbdullahShafique 是的,它只是“细胞”,因为只需要一个

标签: ios uitableview core-data


【解决方案1】:

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

最好使用NSFetchedResultsController。从 Apple 模板开始(如果您创建一个新项目并选择“使用核心数据”,您会得到它),它使用获取的结果控制器。

您的部分设计变得非常简单:只需指定sectionNameKeyPath 属性就足够了。

【讨论】:

  • 您好,如果您能给我一个教程链接,那就太好了...我试过查看东西,但它不起作用
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-23
相关资源
最近更新 更多