

CoreDataへsetし、dismiss()で元の画面に戻ったさい、更新されず。再度アプリを開き直すと、表示されます。末尾にソースコードを記載しています。

・質問  
dismiss()した、もしくは画面が戻った後に、UITableViewを最新のCoreData内に格納された情報を表示させたい（UITableViewを更新させたい）。

・やったこと  
\- tableview.reload() で更新するか試しましたが、更新されませんでした。  
\- 新たに配列を作って、入れ直した配列から情報を取得しましたが、更新しませんでした。

・所感  
CoreData自体にデータが入ってはいるので、dismissした際に何か更新する何かをする必要があると考えています。

よろしくお願い致します。

以下がUITableViewControllerです。

[code]

    import UIKit
    import CoreData
    
    class FriendListViewController: UIViewController, UITableViewDelegate {
    
        @IBOutlet weak var messageLabel: UILabel!
        @IBOutlet weak var friendListTableView: UITableView!
    
        private let persistentContainer = NSPersistentContainer(name: "RecommendPresent")
    
        var friends = [FriendBasicInfo]() {
            didSet {
                updateView()
            }
        }
    
        override func viewDidLoad() {
            super.viewDidLoad()
            doFetch()
        }
    
        override func viewWillAppear(_ animated: Bool) {
            super.viewWillAppear(animated)
            friendListTableView.reloadData()
        }
    
        func setupView() {
            setupMessageLabel()
            updateView()
        }
    
       fileprivate func updateView() {
            var hasFriends = false
    
            if let friends = fetchedResultsController.fetchedObjects {
                print("fetch count \(friends.count)")
                hasFriends = friends.count > 0
            }
    
            friendListTableView.isHidden = !hasFriends
            messageLabel.isHidden = hasFriends
        }
    
        func setupMessageLabel() {
            messageLabel.textAlignment = .center
            messageLabel.text = "You don't have any quotes yet."
        }
    
        func doFetch() {
    
            persistentContainer.loadPersistentStores { (persistentStoreDescription, error) in
                 if let error = error {
                    print("Unable to Load Persistent Store")
                    print("\(error), \(error.localizedDescription)")
    
                } else {
                    self.setupView()
    
                    do {
                        try self.fetchedResultsController.performFetch()
                    } catch {
                        let fetchError = error as NSError
                        print("Unable to Perform Fetch Request")
                        print("\(fetchError), \(fetchError.localizedDescription)")
                    }
                    self.updateView()
                }
            }
        }
    
    
         fileprivate lazy var fetchedResultsController: NSFetchedResultsController<FriendBasicInfo> = {
            // Create Fetch Request
            let fetchRequest: NSFetchRequest<FriendBasicInfo> = FriendBasicInfo.fetchRequest()
    
            // Configure Fetch Request
            fetchRequest.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
    
            // Create Fetched Results Controller
            let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.persistentContainer.viewContext, sectionNameKeyPath: nil, cacheName: nil)
    
            // Configure Fetched Results Controller
            fetchedResultsController.delegate = self
    
            return fetchedResultsController
        }()
    
    }
    
    extension FriendListViewController: UITableViewDataSource {
    
        func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
             guard let friends = fetchedResultsController.fetchedObjects else { return 0 }
                   return friends.count
        }
    
        func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    
            guard let cell = friendListTableView.dequeueReusableCell(withIdentifier: FriendListTableViewCell.reuseIdentifier, for: indexPath) as? FriendListTableViewCell else {
                fatalError("Unexpected Index Path")
            }
    
            let friend = fetchedResultsController.object(at: indexPath)
    
            cell.nameLabel.text = friend.name
            cell.friendImageView.image = friend.photo?.toImage()
    
            return cell
    
        }
    
        func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
            return 80
        }
    }
    
    
    extension FriendListViewController: NSFetchedResultsControllerDelegate {
    
        func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
            friendListTableView.beginUpdates()
        }
    
        func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
            friendListTableView.endUpdates()
    
            updateView()
        }
    
    }
    
[/code]

以下がCoreDataにデータを入力するViewControllerです。

[code]

    import UIKit
    import XLPagerTabStrip
    import Eureka
    import CoreData
    import ImageRow
    
    class InputFriendInforViewController: FormViewController, IndicatorInfoProvider {
    
        var itemInfo: IndicatorInfo = "Info"
        var friendPhoto: UIImage?
        var friendName: String = ""
        var friendBirthday: Date?
        var friendGender: String = ""
    
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
           form +++
    
            Section("Friend Information")
                <<< ImageRow(){
                    $0.title = "Image"
                    $0.sourceTypes = [.PhotoLibrary, .SavedPhotosAlbum, .Camera]
                    $0.value = UIImage(named: "noImage")
                    $0.onChange { [unowned self] row in
                                    self.friendPhoto = row.value!
                                }
                }
                <<< TextRow(){ row in
                    row.title = "Name"
                    row.placeholder = "Enter Name here"
                }.onChange { name in
                    self.friendName = name.value!
                }
                <<< DateRow(){ row in
                    row.title = "Birthday"
                    row.value = Date(timeIntervalSinceReferenceDate: 0)
                }.onChange {date in
                    self.friendBirthday = date.value!
                }
            <<< PushRow<String>(){row in
                    row.title = "Gender"
                    row.options = ["Male","Female","Other"]
                }.onChange {gender in
                    self.friendGender = gender.value!
                }
    
            +++ Section()
                <<< ButtonRow() {
                    $0.title = "SAVE"
                }.onCellSelection {_, _ in
                    self.saveInfo()
                }
        }
    
        // MARK: - IndicatorInfoProvider
    
        func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
            return itemInfo
        }
    
        // save friend Info for Core Data
        func saveInfo (){
    
            guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
    
            let managedContext = appDelegate.persistentContainer.viewContext
            let friendEntity = NSEntityDescription.entity(forEntityName: "FriendBasicInfo", in: managedContext)!
    
            let friendInfo = NSManagedObject(entity: friendEntity, insertInto: managedContext)
    
            // make unique user ID
            let friendUid = NSUUID().uuidString
    
            // Image Data UIImage to png Data
            let pngImage = self.friendPhoto?.toPNGData()
    
            friendInfo.setValue(friendUid, forKey: "userID")
            friendInfo.setValue(pngImage, forKey: "photo")
            friendInfo.setValue(self.friendName, forKey: "name")
            friendInfo.setValue(self.friendBirthday, forKey: "birthday")
            friendInfo.setValue(self.friendGender, forKey: "gender")
    
            do {
                try managedContext.save()
                self.dismiss(animated: true, completion: nil)
            } catch let error as NSError {
                print("Could not save. \(error), \(error.userInfo)")
            }
        }
    }
    
[/code]


CC BY-SA 4.0
2020-02-14T04:58:49.783
63044
2020-02-14T04:58:49.783
36107
question
swift ios swift5 coredata
CoreDataへsetしたデータがUITableViewに反映されない