0

テーブルの下に UILabel を配置できるように、UIViewController 内に UITableView があります。そうすることで、編集/完了ボタンを追加するのに苦労しました。従来の方法ではできなかったので、次のアイデアを使用して回避する必要がありました。

1) viewdidload の左上に編集ボタンを作成します。

self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editbutton)];

2)編集ボタンをクリックすると、テーブルビューが編集可能になり、タイトルが完了に変更されるようにコードを作成します。次に、[完了] をクリックすると、編集と言う状態に戻ります。

-(IBAction)editbutton{
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(donebutton)];
[tableView setEditing:YES animated:YES];

}

-(IBAction)donebutton{
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemEdit target:self action:@selector(editbutton)];

[tableView setEditing:NO animated:YES];

}

この部分は大丈夫です。完全を期すために入れただけです。編集ボタンをクリックするとテーブルビューが編集可能になり、完了をクリックすると通常に戻ります。私の問題は、削除ボタンをクリックしても(行の横にある赤いマイナスボタンをクリックした後)、行が削除されないことです。次のコードを試しました:

注: 1)context は .h ファイルで次のように宣言されています。 @property (非アトミック、保持) NSManagedObjectContext *context; .m ファイルに合成されます。2) .h ファイルで @property (nonatomic、retain) NSFetchedResultsController *fetchedResultsController を宣言し、.m ファイルで @synthesize fetchedResultsController = _fetchedResultsController を宣言しました。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {

    // Delete the managed object for the given index path
    [context deleteObject:[_fetchedResultsController objectAtIndexPath:indexPath]];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
}   
}

編集:

わかりました、私は少し解決策を見つけました。次のコードを使用して、コア データを削除しました。

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the managed object for the given index path
    NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
    [context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];

    // Save the context.
    NSError *error = nil;
    if (![context save:&error]) {
        /*
         Replace this implementation with code to handle the error appropriately.

         abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. 
         */
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        abort();
    }
    [self fetchedresults];
    [self.tableView reloadData];

}   
}

私の新しい問題は、削除をクリックしたときです。行は削除されますが、空白の行に赤いマイナス ボタンが表示されたまま残ります。行をクリックすることもできますが (通常はデータを編集します)、ロードするデータがありません。

編集2:

追加するのを忘れて、それを機能させるために、これを追加しました:

- (NSFetchedResultsController *)fetchedResultsController{

if (_fetchedResultsController != nil) {
    return _fetchedResultsController;
}

// Set up the fetched results controller.
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Record" inManagedObjectContext:context];
[fetchRequest setEntity:entity];

// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];

// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"activity" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sortDescriptor, nil];

[fetchRequest setSortDescriptors:sortDescriptors];

// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:@"Master"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;

NSError *error = nil;
if (![self.fetchedResultsController performFetch:&error]) {


    NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
    abort();
}

return _fetchedResultsController;
}

編集3:

取得した結果は次のようになります。

- (void)fetchedresults {

NSManagedObjectContext *moc = [self context];
NSEntityDescription *entityDescription = [NSEntityDescription
                                          entityForName:@"Record" inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];


NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]
                                    initWithKey:@"activity" ascending:YES];
[request setSortDescriptors:[NSArray arrayWithObject:sortDescriptor]];

NSError *error = nil;
NSArray *array = [moc executeFetchRequest:request error:&error];
if (array == nil)
{
    // Deal with error...
}

float tot = [[array valueForKeyPath:@"@sum.cpdhours"] floatValue]; 
totalhours.text =  [NSString stringWithFormat:@"%.1f", tot];


}
4

4 に答える 4

1

あなたが持っているmanagedObjectContextプロパティは、実際にはfetchedResultsControllerコンテキストの親コンテキストであると思います。したがって、それを使用してエンティティを削除すると、fetchedResultsControllerは、テーブルビューを再フェッチして更新することになっていることを認識しません。[self.fetchedResultsController.managedObjectContext deleteItem:yourItem]を呼び出してみてください。

たぶん、私がiPhoneでこれを書いているのとまったく同じではないかもしれませんが、あなたはその考えを理解しています。また、テーブルビューを更新するために、フェッチされた結果コントローラーのデリゲートメソッドを実装していることを確認しましたか?

于 2012-04-29T13:01:24.033 に答える
1

おそらく、NSResultFetchedController を再キャッシュする必要があります。NSFetchedResultController init 関数では、フェッチ結果を「Master」という名前のキャッシュにキャッシュしています。これはおそらく、あなたが経験している行動を説明しています。

NSFetchedResultController を設定するときにキャッシュ名を nil に設定することで、キャッシュを使用しないようにすることができます。

NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:context sectionNameKeyPath:nil cacheName:nil];

または、NSManagedObject を削除した直後にキャッシュを削除します。

[NSFetchedResultController deleteCacheWithName:@"Master"];
于 2012-04-30T02:48:14.217 に答える
0

使用していNSFetchedResultsControllerますか?そうでない場合は、試してみてください。テーブルのリロードについてはまったく心配する必要はありません。


また、カスタムボタンを使用する必要はまったくありません。に固執し、.editButtonItemオーバーライドするだけ-setEditing:animated:です。

- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
    [super setEditing:editing animated:animated];
    [self.tableView setEditing:editing animated:animated];
}
于 2012-04-29T15:46:13.487 に答える
0

Swift : 私の場合tableView、ユーザーがサインアウトした後に完全に消去したい:

func clearData(){
    NSFetchedResultsController.deleteCacheWithName("MyCache")

    let indices = tableView.allIndices
    let moc = NSManagedObjectContext.MR_defaultContext()
    let fetchRequest = NSFetchRequest(entityName: "MyEntity")
    let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
    saveMoc()

    do {
        try moc.persistentStoreCoordinator!.executeRequest(deleteRequest, withContext: moc)
        try fetchedResultsController.performFetch()
        tableView.beginUpdates()
        tableView.deleteRowsAtIndexPaths(indices, withRowAnimation: .Automatic)
        tableView.endUpdates()

    } catch let e as NSError {
        print(e)
    }
}

NSIndexPathテーブルビューのすべてのsを取得する拡張機能を作成しました。

extension UITableView{
    var allIndices: [NSIndexPath] {
        var indices = [NSIndexPath]()
        let sections = self.numberOfSections
        if sections > 0{
            for s in 0...sections - 1 {
                let rows = self.numberOfRowsInSection(s)
                if rows > 0{
                    for r in 0...rows - 1{
                        let index = NSIndexPath(forRow: r, inSection: s)
                        indices.append(index)
                    }
                }
            }
        }
        return indices
    }
}
于 2016-03-25T23:15:45.050 に答える