2012-04-29 9 views
0

UIViewController内にUITableViewがあり、テーブルの下に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]; 

} 

この部分はすべてOKです。私はちょうど完成のためにそれを入れました。編集ボタンをクリックするとテーブルビューが編集可能になり、完了をクリックして通常に戻ります。私の問題は、行の横にある赤いマイナスボタンをクリックした後、削除ボタンをクリックしても行が削除されないということです。私は、次のコードを試してみました:

注: 1)コンテキストとして.hファイルで宣言されています @property(アトミック、保持)NSManagedObjectContext *コンテキスト。 であり、.mファイルで合成されます。 2)私はその後@property .hファイルで(非アトミック、保持)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(); 
    } 
} 
} 

EDIT:

さて、私は少し解決策を見つけました。

- (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]; 

} 
} 

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

EDIT 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; 
} 

EDIT 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]; 


} 

答えて

0

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


また、カスタムボタンを使用する必要はありません。 .editButtonItemに固執し、-setEditing:animated:を上書きしてください。

- (void)setEditing:(BOOL)editing animated:(BOOL)animated 
{ 
    [super setEditing:editing animated:animated]; 
    [self.tableView setEditing:editing animated:animated]; 
} 
+0

2番目の部分がうまくいきました!!!ありがとう!!しかし、答えの最初の部分に関しては、編集2を参照してください。NSFetchedResultsControllerを使用していて、それでもまだ更新されません。 – spudsta

+0

'[self fetchedresults ]; do? –

+0

私の新しい編集を参照してください。他の画面から戻ってくるときにデータを更新するためにうまく働いたビューコントローラが取得されたと思います。 – spudsta

1

あなたが持っているmanagedObjectContextプロパティは、実際はあなたのfetchedResuの親コンテキストですltsControllerコンテキストを使用しているため、それを使用してエンティティを削除すると、fetchedResultsControllerはテーブルビューを再取得して更新するはずです。 [self.fetchedResultsController.managedObjectContext deleteItem:yourItem]を呼び出してみてください。

私のiPhoneにこれを書いているのとまったく同じではないかもしれないが、あなたはそのアイデアを得る。また、フェッチされた結果コントローラのデリゲートメソッドを実装して、テーブルビューを更新するようにしましたか?

+0

コード[self.fetchedResultsController.managedObjectContext deletedObjects:[_ fetchedResultsController objectAtIndexPath:indexPath]を使用して試行しました。 ]。 as deleteitemは無効ですが、コードにエラーがあります。レシーバタイプNSManagedObjectContext(インスタンスmessageはセレクタ 'deleted objects'を持つメソッドを宣言しません)また、エラーは、テーブルの更新前に発生します。上記のエラーステートメントでエラーが発生しました(NSLog(@ "未解決のエラー%@、%@"、エラー、[エラーuserInfo]) – spudsta

+0

[self.fetchedResultsController.managedObjectContext deleteObject:self.objectToDelete] これは私のコードからです –

1

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

あなたはどちらかNSFetchedResultController

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

またはあなたがあなたのNSManagedObjectを削除した直後にキャッシュを削除を設定するときnilにキャッシュ名を設定することにより、任意のキャッシュを使用することはできません。

[NSFetchedResultController deleteCacheWithName:@"Master"]; 
0

スウィフトは:私の場合、私は完全にユーザーがサインした後、私のtableViewを一掃したい:私は私のテーブルビューのすべてのNSIndexPath Sを取得するための拡張を行った

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) 
    } 
} 

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 
    } 
} 
関連する問題