2017-04-24 3 views
0

この問題に関連するすべてQ & Aを通過しましたが、コードが古すぎるか、問題が簡単すぎる(つまり、基本的な文字列のような単純なデータをtableviewに送る方法は、コアデータエンティティでは機能しません)コアデータオブジェクトが削除された後、ナビゲーションコントローラの戻るボタンがテーブルビューを更新する必要があります。xCode 8.3.1

私はコアデータエンティティからのレコードのテーブルビューを持っています。レコードを選択すると、詳細ビ​​ューに移動します。ユーザーはそこからレコードを削除できます。しかし、ナビゲーションコントローラの「戻る」ボタンが押され、ユーザがテーブルビューに戻されると、レコードはテーブルにまだ表示されます。

私はオブジェクトが削除されていることを知っています。これは、1つの画面をさらに進めてから、テーブルビューを更新するとオブジェクトが更新され、オブジェクトがレコードのリストに表示されなくなるからです。

テーブルビューを更新するために戻るボタンを取得する簡単な方法が必要ですか?しかしどうですか?

私はスウィフトに新たなんだので、コード例が

おかげ

**********************編集をいただければ幸いです** ************************ここ

はRecordView又は2ビューコントローラ

@IBAction func Delete(_ sender: UIButton) { // The delete function 

    let alertContoller = UIAlertController(title: "Delete?", message: "Are you sure? This can't be undone", preferredStyle: .actionSheet)// This is the alert message 
    let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil) // These are the alert actions 

    let deleteAction = UIAlertAction(title: "Delete", style: .default) { (action) in //defining the delete action 

       func deleteRecords() -> Void { //The function to delete the record 
        let moc = getContext() 
        let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "DestinationsOne") // The fetch request 
        let result = try? moc.fetch(fetchRequest) 
        let resultdata = result as! [DestinationsOne] // result as entity 

        for object in resultdata { // Go through the fetched result 
         if object.destID == self.IDTitle{ // If there is a match 
         moc.delete(object) // delete the object 
         } 
        } 
        do { 
         try moc.save() // Save the delete action 
        } catch let error as NSError { 
         print("Could not save \(error), \(error.userInfo)") 
        } catch { 

        } 

       } 
       func getContext() -> NSManagedObjectContext { // The get context function 
        let appDelegate = UIApplication.shared.delegate as! AppDelegate // The appdelegate as a shared delegate 
        return appDelegate.persistentContainer.viewContext // Persistent container is where the objects are stored 
       } 

       deleteRecords() // Call the function 

そしてユーザヒットのためのコードであります戻り値は、ResultsViewというTableViewに戻ります。 問題のレコードは削除されていますが、依然としてレコードのリストに表示されます。

はここにtableViewからのコードです:

class ResultsView: UIViewController, UITableViewDelegate, UITableViewDataSource { 




@IBOutlet weak var tableView: UITableView! 

override func viewDidLoad() { 
    super.viewDidLoad() 

    tableView.delegate = self // Sets the delegate for the tableview to self 
    tableView.dataSource = self // Sets the datasource to self 

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DestinationsOne") // The request to retrieve the data from the database 
    let context = appDelagate.persistentContainer.viewContext // Persistant container allows the data to be saved by core data 


    do { 
     try destArray = context.fetch(request) as! [DestinationsOne]} // Putting the data into an array for processing 
    catch{ 
     //error message 
    } 


    // Do any additional setup after loading the view. 
} 

var seasonArray = [DestinationsOne]() // The array to hold search results from find by season 
var destArray = [DestinationsOne]() // The full data array 

let appDelagate = UIApplication.shared.delegate as! AppDelegate // The appdelegate as a shared delegate 

public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Function copied from UITableView Source 
    if seasonArray.count > 0{ // If there are elements in seasonArray 
     return seasonArray.count // sets the number of rows to the number of the seasonArray's destination objects 
    }else{ // If not 
     return destArray.count // sets the number of rows to the number of the destArray's destination objects 
    } 
} 
// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier: 
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls) 

public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{ // Function copied from UITableView Source 

    let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell // Recycle cells for scrollng 

    if seasonArray.count > 0{ // If there are elements in seasonArray 

    cell.Destination.text = seasonArray[indexPath.row].destName //Sets the text in the cell 
    if seasonArray[indexPath.row].destImage == nil{ // A check to make sure the image doesn't return nil and cause a crash 
     cell.Picture.image = UIImage(named:"Generic.png")! 

    }else{ // if not 

     cell.Picture.image = UIImage(data: seasonArray[indexPath.row].destImage! as Data) // The table image is either a default image or the image of record 
    } 

    return cell 

    }else{ // If seasonArray is empty 
     cell.Destination.text = destArray[indexPath.row].destName //Sets the text in the cell 
     if destArray[indexPath.row].destImage == nil{ // A check to make sure the image doesn't return nil and cause a crash 
      cell.Picture.image = UIImage(named:"Generic.png")! 
     }else{ 
      cell.Picture.image = UIImage(data: destArray[indexPath.row].destImage! as Data) // The table image is either a default image or the image of record 
     } 

     return cell 


    } 
} 
+0

いくつかの方法があります。既存のコードを表示すると、状況に応じて最適なコードが表示されます。 – pbasdf

答えて

0

が、私はそれを考え出しました。 viewWillAppearのreloadDataはレコードを削除しますが、クリックするとプレースホルダが残ってアプリがクラッシュします。解決方法は、ViewDidLoadにあるコードをViewWillAppearにも移動することです。

override func viewWillAppear(_ animated: Bool) { 

    tableView.delegate = self // Sets the delegate for the tableview to self 
    tableView.dataSource = self // Sets the datasource to self 

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "DestinationsOne") // The request to retrieve the data from the database 
    let context = appDelagate.persistentContainer.viewContext // Persistant container allows the data to be saved by core data 


    do { 
     try destArray = context.fetch(request) as! [DestinationsOne]} // Putting the data into an array for processing 
    catch{ 
     //error message 
    } 


    tableView.reloadData() 

} 


override func viewDidLoad() { 
    super.viewDidLoad() 


    // Do any additional setup after loading the view. 
}