- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在构建一个简单的应用程序,我可以在其中将餐食(食物)添加到列表中,然后使用另一个 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()
}
}
应用程序委托(delegate):
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
}
}
并从 View Controller 使用返回的值来填充 TableView 数组
关于ios - 有人可以看到我在尝试使用 coreData 保存事件时缺少什么吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59708610/
如何获取特定 UTF-8 字符串的字节序列?我看到正则表达式引擎中的某些错误仅在某些边缘情况下才会触发,我想确切地知道它正在处理哪些数据。 最佳答案 也许 charToRaw ? > charToRa
考虑一个具有许多变量的 java 程序,其中一些是循环计数器,我希望看到这些变量随时间变化的值,而不是在代码中到处放置 print 语句。 为什么?我认为它可以帮助我轻松调试。 Example- in
有没有办法查看 JavaScript 正在创建的“线程”?例如,如果我有一个附加到 DOM 元素的事件处理程序,我假设 JavaScript 会隐式地创建一个新线程来在后台运行该代码?如果是这样,有没
我正在使用反射 API 来调用类运行时并调用其方法。但我看到 java.lang.reflect.InitationTargetException 异常。 我需要调用一个名为 - TestClass
考虑一个名为 t.cmd 的命令脚本,它只包含以下两行: @exit /b 123 @echo If you see this, THEN EXIT FAILED.. 因此,该脚本只是将脚本执行过程的
我最近一直在努力学习编程语言实用学第 3 版,以了解更多关于语言在底层如何工作的信息,并且通过查看由真正基本的 GCC 编译的 C 代码生成的程序集,我获得了很多进展.我开始对 C 系列的静态语言越来
最简单的制作方法是什么QWebView识别并正确加载网页上的 Flash? 最佳答案 似乎只需两行即可实现(当然,假设目标系统上安装了闪存): QWebSettings *settings = QWe
我想通过编程(使用VBA)访问其他人与我共享的日历。它们在我的Outlook中的“人民日历”下列出。我在网上搜索了此内容,所有建议所做的仅使我感到困惑。如何从“人的日历”中获取共享给我的所有日历的
使用MongoDB Compass,可以看到数据库用户或创建新用户吗? 最佳答案 香港专业教育学院在命令行上使用以下命令进行管理: mongo use (my database name) db.cr
我正在CentOS 7.4.1708(核心),Java(TM)SE运行时环境(内部版本1.8.0_152-b16)上运行eXist-db 3.6.1。我希望能够在person.xml中的最后一个记录之
我需要确认。 客户端 1 在事务内的表中插入行。 客户端 2 使用 SELECT 请求该表。如果在此客户端上隔离级别设置为 READ COMMITTED,您能否确认 SELECT 不会返回客户端 1
我刚刚安装了 python-dev: $ sudo apt-get install python-dev 这样我就可以开始使用 P4Python 了。但是当我尝试导入 P4 时,我得到: Traceb
我正在使用 msys 和 mingw 编译 libtorrent-rasterbar-0.16.16。./configure 运行良好,直到它进入 boost 库检查。我有 boost 1.51,我设
我在 GO 项目的 Travis CI 上有一个奇怪的行为。 [这里] 失败了,提示一个函数只接受 1 个参数并用 2 个参数调用。 src/finances-service/main.go:45:1
这个问题已经有答案了: What are enums and why are they useful? (27 个回答) 已关闭 4 年前。 作为 Java 初学者,我接触到了枚举,这让我对类型声明感
关闭。这个问题是off-topic .它目前不接受答案。 想改进这个问题吗? Update the question所以它是on-topic用于堆栈溢出。 关闭 11 年前。 Improve thi
我正在使用 preactjs 创建我的应用程序。最重要的是,我正在使用剑道网格。在网格内,我想显示一个超链接。如果用户点击链接,它应该改变路线。为了呈现链接,我使用了 preact-router。 这
有没有办法只查看 Node.js 中的函数签名?我知道 fn.toString() 但不需要所有代码,只需要签名。 最佳答案 var source = fn.toString(); var signa
如何设置 vim 以查看我在 ubuntu 上安装的 ruby rvm。 rvm 已安装,ruby 从终端返回。 renshaw@renshaw-TravelMate-5740G:~$ ruby
我试图在我的 Android 应用程序中防止 OutOfMemoryError。我已经阅读了很多帖子,但我仍然无法解决。 该应用程序有后台 Activity ,所以我认为这是主要问题。 OutOfMe
我是一名优秀的程序员,十分优秀!