1

私のアプリでは、ユーザーは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 にはこの 3 つのセクション (ヘッダー) しかありませんが、それらにセルを追加することはできません。例: ユーザーが新しいセルにUSAを選択した場合、このセルはUSAセクションに表示されます。

4

1 に答える 1

0

データソース メソッドに欠陥があります。たとえば、各セクションに同じセル データを返しているとします。他にも問題があります。

を使用する方がはるかに優れていますNSFetchedResultsController。フェッチされた結果コントローラーを使用する Apple テンプレート (新しいプロジェクトを作成し、[コア データを使用] を選択した場合に得られます) から開始します。

その場合、セクションの設計は非常に単純になります。単純にsectionNameKeyPathプロパティを指定するだけで十分です。

于 2013-08-09T11:27:27.987 に答える