2016-11-25 117 views
0

我保存的鍛鍊到核心數據,把它插入表中,這部作品在攜帶來自用戶輸入的信息到表中的條款,但是coredata犯規持續存在,因此當我重新打開應用程序時,該條目丟失。核心數據不會持續嗎?

它實際上是工作昨天似乎已經打破,但我還沒有做出改變,將盡可能實現這種作爲即時通訊知道。我在調試時發現的一件事是,當我加載應用程序時,它的意思是指向我的控制檯中的sql數據庫,但是它已更改爲.configurationprofiles文件?這可能是一個原因,修復會是什麼?我將包含tableview的代碼和下面的用戶輸入表單的代碼來顯示信息流。讓我知道是否需要添加任何其他數據。

enter image description here

import Foundation 
import UIKit 
import CoreData 

class ExerciseEditorController: UIViewController, UITextFieldDelegate { 

    var managedObjectContext: NSManagedObjectContext? 

    var userRepsCount = Int() 
    var userSetsCount = Int() 

    @IBOutlet weak var userExerciseName: UITextField! 
    @IBOutlet weak var userExerciseSetCounter: UILabel! 
    @IBOutlet weak var userExerciseRepsCounter: UILabel! 
    @IBOutlet weak var userExerciseWeight: UITextField! 

    @IBAction func userSetsStepper(_ sender: UIStepper) { 
     userExerciseSetCounter.text = Int(sender.value).description 
     self.userSetsCount = Int(sender.value) 
    } 

    @IBAction func userRepsStepper(_ sender: UIStepper) { 
     userExerciseRepsCounter.text = Int(sender.value).description 
     self.userRepsCount = Int(sender.value) 
    } 

    @IBAction func cancelExerciseEditor(_ sender: Any) { 
     self.performSegue(withIdentifier: "unwindToWorkoutDesignerWithSegue:", sender: self) 
    } 

    @IBAction func saveExerciseToWorkout(_ sender: Any) { 

     createExercise() 
     self.performSegue(withIdentifier: "unwindToWorkoutDesignerWithSegue:", sender: self) 
    } 

    override func viewDidLoad() { 
     super.viewDidLoad() 

     view.backgroundColor = (UIColor.customBackgroundGraphite()) 

     userExerciseSetCounter.text = String(userSetsCount) 
     userExerciseRepsCounter.text = String(userSetsCount) 
     userExerciseWeight.delegate = self 
     userExerciseWeight.keyboardType = .numbersAndPunctuation 

    } 

    func createExercise() { 
     let userExerciseWeightSet = Double(self.userExerciseWeight.text!) //make this safe! 

     guard let managedObjectContext = managedObjectContext else { return } 

     let userExercise = UserExercise(context: managedObjectContext) 

     userExercise.name = userExerciseName.text 
     userExercise.sets = Int64(userSetsCount) 
     userExercise.reps = Int64(userRepsCount) 
     userExercise.weight = userExerciseWeightSet! //make this safe! 
     userExercise.createdAt = Date().timeIntervalSince1970 

    } 

    func animateTextField(textField: UITextField, up: Bool) { 
     let movementDistance:CGFloat = -130 
     let movementDuration: Double = 0.3 
     var movement:CGFloat = 0 
     if up { 
      movement = movementDistance 
     } 
     else { 
      movement = -movementDistance 
     } 

     UIView.beginAnimations("animateTextField", context: nil) 
     UIView.setAnimationBeginsFromCurrentState(true) 
     UIView.setAnimationDuration(movementDuration) 
     self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement) 
     UIView.commitAnimations() 
    } 

    func textFieldDidBeginEditing(_ textField: UITextField) { 
     self.animateTextField(textField: textField, up:true) 
    } 

    func textFieldDidEndEditing(_ textField: UITextField) { 
     self.animateTextField(textField: textField, up:false) 
    } 

} 

而這正是實現代碼如下:

import Foundation 
import UIKit 
import CoreData 

class WorkoutDesignerController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate { 

    @IBAction func unwindToWorkoutDesigner(segue: UIStoryboardSegue) {} 
    @IBOutlet weak var workoutDesignerTable: UITableView! 
    @IBOutlet weak var tapToAddExercise: UILabel! 
    @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! 
    @IBAction func cancelWorkoutDesigner(_ sender: Any) { 
     self.performSegue(withIdentifier: "unwindToTemplatesWithSegue", sender: self) 
    } 

    private let persistentContainer = NSPersistentContainer(name: "Lift") 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     setupView() 
     workoutDesignerTable.delegate = self 
     workoutDesignerTable.dataSource = self 

     view.backgroundColor = (UIColor.customBackgroundGraphite()) 

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

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     guard let userExercises = fetchedResultsController.fetchedObjects else { return 0 } 
     return userExercises.count 
    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     guard let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as? RoutineTableViewCell else { 
      fatalError("Unexpected Index Path") 
     } 

     cell.backgroundColor = UIColor.customBackgroundGraphite() 
     cell.textLabel?.textColor = UIColor.white 

     let userExercise = fetchedResultsController.object(at: indexPath) 

     cell.nameLabel.text = userExercise.name 
     cell.repsLabel.text = String(userExercise.reps) 
     cell.setsLabel.text = String(userExercise.sets) 
     cell.weightLabel.text = String(userExercise.weight) 

     return cell 
    } 

    private func setupView() { 
     setupMessageLabel() 
     updateView() 
    } 

    private func setupMessageLabel() { 
     tapToAddExercise.text = "Tap + To Add An Exercise To The Routine" 
    } 

    fileprivate func updateView() { 
     var hasUserExercises = false 
     if let UserExercise = fetchedResultsController.fetchedObjects { 
      hasUserExercises = UserExercise.count > 0 
     } 
     workoutDesignerTable.isHidden = !hasUserExercises 
     tapToAddExercise.isHidden = hasUserExercises 

     activityIndicatorView.stopAnimating() 
    } 

    fileprivate lazy var fetchedResultsController: NSFetchedResultsController<UserExercise> = { 

     // Create Fetch Request 
     let fetchRequest: NSFetchRequest<UserExercise> = UserExercise.fetchRequest() 

     // Configure Fetch Request 
     fetchRequest.sortDescriptors = [NSSortDescriptor(key: "createdAt", 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 
    }() 

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     if segue.identifier == "addNewExerciseSegue" { 
      if let destinationViewController = segue.destination as? ExerciseEditorController { 
       // Configure View Controller 
       destinationViewController.managedObjectContext = persistentContainer.viewContext 
      } 
     } 
    } 

    func controllerWillChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { 
     workoutDesignerTable.beginUpdates() 
    } 

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) { 
     workoutDesignerTable.endUpdates() 

     updateView() 
    } 

    func controller(_ controller: NSFetchedResultsController<NSFetchRequestResult>, didChange anObject: Any, at indexPath: IndexPath?, for type: NSFetchedResultsChangeType, newIndexPath: IndexPath?) { 
     switch (type) { 
     case .insert: 
      if let indexPath = newIndexPath { 
       workoutDesignerTable.insertRows(at: [indexPath], with: .fade) 
      } 
      break; 
     default: 
      print("...") 
     } 
    } 

} 
+1

爲了使數據持久化,你必須保存管理對象上下文。 – vadian

+0

這是保存按鈕功能saveexercise中實現的功能嗎? – infernouk

+0

不,您正在創建實例,但不保存上下文。某處你必須調用'context.save()' – vadian

回答

0

你需要調用context.save()