ios - 尝试使用 coreData 保存我的事件时,有人能看到我缺少什么吗?
问题描述
我正在构建一个简单的应用程序,我可以在其中将餐点(食物)添加到列表中,然后使用来自另一个 VC 的 UIPicker 来挑选这些餐点。这很好用,但我无法保存它。(重新启动后不保存数据)。我正在尝试使用 coreData 执行此操作,我可以在代码列表中看到事件/更改实际上正在保存和加载。(我已经在其他应用中成功使用过coreData)
谁能帮我?我应该怎么办?我对 IOS 开发和 Swift 还很陌生,所以请明确具体=)
这是我的代码:
请告诉我您是否需要其他帮助我。非常感谢 StackOverflow!
VC 1:
import UIKit
import CoreData
var List = ["Pasta Pesto", "Spenat Soppa", "Ris, Quorn & Currysås", "Lins Soppa"]
class ViewController: UIViewController {
@IBOutlet weak var monday: UITextField!
@IBOutlet weak var tuesday: UITextField!
@IBOutlet weak var wednesday: UITextField!
@IBOutlet weak var thursday: UITextField!
@IBOutlet weak var friday: UITextField!
@IBOutlet weak var saturday: UITextField!
@IBOutlet weak var sunday: UITextField!
var daysArray = [UITextField]()
let pickerView = ToolbarPickerView()
var selectedMenu : String?
override func viewDidLoad() {
super.viewDidLoad()
setupDelegateForPickerView()
setupDelegatesForTextFields()
coredataClass.loadData()
}
func setupDelegatesForTextFields() {
//appending textfields in an array
daysArray += [monday, tuesday, wednesday, thursday, friday, saturday, sunday]
//using the array to set up the delegates, inputview for pickerview and also the inputAccessoryView for the toolbar
for day in daysArray {
day.delegate = self
day.inputView = pickerView
day.inputAccessoryView = pickerView.toolbar
}
}
func setupDelegateForPickerView() {
pickerView.dataSource = self
pickerView.delegate = self
pickerView.toolbarDelegate = self
}
}
// Create an extension for textfield delegate
extension ViewController : UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
self.pickerView.reloadAllComponents()
}
}
// Extension for pickerview and toolbar
extension ViewController : UIPickerViewDelegate, UIPickerViewDataSource {
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return List.count
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return List[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
// Check if the textfield isFirstResponder.
if monday.isFirstResponder {
monday.text = List[row]
} else if tuesday.isFirstResponder {
tuesday.text = List[row]
} else if wednesday.isFirstResponder {
wednesday.text = List[row]
} else if thursday.isFirstResponder {
thursday.text = List[row]
} else if friday.isFirstResponder {
friday.text = List[row]
} else if saturday.isFirstResponder {
saturday.text = List[row]
} else if sunday.isFirstResponder {
sunday.text = List[row]
} else {
//log errors
}
}
// PickerView's didSelectRow function can be simplified by changing it to below
// func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
//
// for day in daysArray {
// if day.isFirstResponder {
// day.text = self.Menu[row]
// }
// }
// }
}
extension ViewController: ToolbarPickerViewDelegate {
func didTapDone() {
// let row = self.pickerView.selectedRow(inComponent: 0)
// self.pickerView.selectRow(row, inComponent: 0, animated: false)
// selectedMenu = self.Menu[row]
self.view.endEditing(true)
}
func didTapCancel() {
self.view.endEditing(true)
}
}
VC 2:
import UIKit
import CoreData
class addViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var input: UITextField!
@IBAction func addToMenu(_ sender: Any) {
if (input.text != "")
{
List.append(input.text!)
input.text = ""
}
input.delegate = self
coredataClass.saveItems()
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
self.view.endEditing(true)
}
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
input.resignFirstResponder()
return true
}
}
VC 3:
import UIKit
import CoreData
class tableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource{
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (List.count)
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
cell.textLabel?.text = List[indexPath.row]
cell.textLabel?.textColor = UIColor.white
cell.backgroundColor = UIColor.clear
return(cell)
}
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == UITableViewCell.EditingStyle.delete
{
List.remove(at: indexPath.row)
myTableView.reloadData()
}
}
@IBOutlet weak var myTableView: UITableView!
override func viewDidAppear(_ animated: Bool) {
myTableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
coredataClass.saveItems()
coredataClass.loadData()
}
}
应用委托:
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "bonAPPetit")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() 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.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
核心数据类:
import UIKit
import CoreData
class coredataClass {
static var items = [MealsMenu]()
static let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
static func saveItems(){
do{
try coredataClass.context.save()
print("SAVED")
}catch{
print("Error saving context with")
}
}
static func loadData(){
let request: NSFetchRequest<MealsMenu> = MealsMenu.fetchRequest()
do{
items = try coredataClass.context.fetch(request)
print("LOADED")
}catch{
print("Error fetching data from context")
}
}
}
解决方案
coreData 类中的 loadData 方法在获取成功后不会返回项目,因此要么从该方法返回,要么在获取成功后使用闭包
static func loadData()->[MealsMenu]{
let request: NSFetchRequest<MealsMenu> = MealsMenu.fetchRequest()
do{
items = try coredataClass.context.fetch(request)
return items
print("LOADED")
}catch{
print("Error fetching data from context")
return items
}
}
并从视图控制器使用返回的值来填充表视图数组
推荐阅读
- javascript - Google Firestore 监听实时更新
- node.js - 赛普拉斯:在“之前:运行”中执行命令
- sql - 如何只选择表中符合条件的行,避免 SQL 中的重复
- react-native - 我可以在 Expo 平台上测试 OneSignal 推送通知吗?
- python - 对于非 16 位文件,pydub 音频播放*非常*响亮
- istio - istio-ingressgateway 健康检查失败
- cmake - CMAKE's undefined variable in document 3.21.but 可以使用
- tensorflow - 检查失败:使用 Keras 时出现 cudnnSetTensorNdDescriptor 错误
- google-api - youtube-api是否有一种关于视频版权摘要和状态的方法?
- javascript - d3js直线颜色被其他线条覆盖