ios - 核心数据似乎没有保存
问题描述
我正在尝试创建一个应用程序,该应用程序要求用户在被允许进入应用程序的其余部分之前成功输入 pin。我做了一些搜索,发现一个基本的现有 coredata 示例应用程序可以在这里工作。
我进入 xcdatamodel 并删除了它们的属性并替换为“pin”,它是一个字符串。这是 xcdatamodel 的屏幕截图。
然后我修改了 ViewController,以便 createData UI 按钮打开一个 alertController,提示用户输入新的 pin 两次,检查它们是否相同,如果它们相同,它会使用该 pin 创建一个 coredata 条目。
下面是 ViewController 的相关代码:
import UIKit
import CoreData
class ViewController: UIViewController {
var firstPinNumber:String = ""
var secondPinNumber:String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func createData(_ sender: Any) {
let enterPinAlertController = UIAlertController(title: "Enter New PIN", message: "", preferredStyle: .alert)
enterPinAlertController.addTextField{ (textField1:UITextField)->Void in
textField1.placeholder = "Enter PIN"
textField1.isSecureTextEntry = true
}
enterPinAlertController.addTextField{ (textField2:UITextField)->Void in
textField2.placeholder = "Re-Enter PIN"
textField2.isSecureTextEntry = true
}
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
if let textFields = enterPinAlertController.textFields {
let theTextFields = textFields as [UITextField]
self.firstPinNumber = theTextFields[0].text!
self.secondPinNumber = theTextFields[1].text!
if self.firstPinNumber != self.secondPinNumber {
print ("PINs dont match!")
let pinsDontMatchAlertController = UIAlertController(title: "PINs don't match!", message: "Try again", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
}
pinsDontMatchAlertController.addAction(okAction)
self.present(pinsDontMatchAlertController, animated: true, completion: nil)
}
}
}
enterPinAlertController.addAction(okAction)
self.present(enterPinAlertController, animated: true, completion: nil)
createPIN(pinNum: secondPinNumber)
}
func createPIN(pinNum: String){
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Now let’s create an entity and new user records.
let userEntity = NSEntityDescription.entity(forEntityName: "User", in: managedContext)!
let user = NSManagedObject(entity: userEntity, insertInto: managedContext)
user.setValue(pinNum, forKeyPath: "pin")
print(user.value(forKey: "pin") as Any)
//Now we have set the pin. The next step is to save it inside the Core Data
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
@IBAction func retrieveData(_ sender: Any) {
let storedPin = retrievePIN()
print(storedPin)
}
func retrievePIN()->String {
var storedPin:String = ""
//As we know that container is set up in the AppDelegates so we need to refer that container.
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return "" }
//We need to create a context from this container
let managedContext = appDelegate.persistentContainer.viewContext
//Prepare the request of type NSFetchRequest for the entity
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "User")
fetchRequest.fetchLimit = 1
// fetchRequest.predicate = NSPredicate(format: "username = %@", "Ankur")
// fetchRequest.sortDescriptors = [NSSortDescriptor.init(key: "email", ascending: false)]
//
do {
let result = try managedContext.fetch(fetchRequest)
for data in result as! [NSManagedObject] {
if data.value(forKey: "pin") != nil {
storedPin = data.value(forKey: "pin") as! String
print(storedPin)
} else {
print ("Found nil")
}
}
} catch {
print("Failed")
}
return storedPin
}
使用断点我已经确定它进入了 createPin() 函数,但它似乎在它呈现 enterPinAlertController 以输入新引脚之前进入了该函数,即使在呈现 enterPinAlertController 之后调用 createPin() 也是如此。
另外,如果我使用retrieveData UIButton,它会打印出“Found nil”
因此,如果我的想法是正确的,它会创建一个带有空字符串的 coredata 条目,还是什么都没有?我该如何解决这个问题,以便它使用用户输入的字符串作为新引脚创建一个 coredata 条目,并在以后检索它?
解决方案
您的调用createPin
需要在okAction
. 正如您现在所拥有的,secondPinNumber
将在显示警报之前调用它,因此它将为空或nil
,具体取决于您如何初始化它。
IBAction func createData(_ sender: Any) {
let enterPinAlertController = UIAlertController(title: "Enter New PIN", message: "", preferredStyle: .alert)
enterPinAlertController.addTextField{ (textField1:UITextField)->Void in
textField1.placeholder = "Enter PIN"
textField1.isSecureTextEntry = true
}
enterPinAlertController.addTextField{ (textField2:UITextField)->Void in
textField2.placeholder = "Re-Enter PIN"
textField2.isSecureTextEntry = true
}
let okAction = UIAlertAction(title: "OK", style: .cancel) {(action) in
if let textFields = enterPinAlertController.textFields,
let firstPinNumber = textFields[0].text,
let secondPinNumber = textFields[1].text,
firstPinNumber == secondPinNumber {
createPIN(pinNum: secondPinNumber)
} else {
print ("PINs dont match!")
let pinsDontMatchAlertController = UIAlertController(title: "PINs don't match!", message: "Try again", preferredStyle: .alert)
let okAction = UIAlertAction(title: "OK", style: .cancel)
pinsDontMatchAlertController.addAction(okAction)
self.present(pinsDontMatchAlertController, animated: true, completion: nil)
}
}
}
enterPinAlertController.addAction(okAction)
self.present(enterPinAlertController, animated: true, completion: nil)
}
推荐阅读
- c# - SSIS 错误:找不到脚本的二进制代码
- ios - How can I decode JSON with array and more JSON inside?
- jquery - FullCalendar - 在周和月视图的 x 轴上显示用户,在 y 轴上显示时间
- c# - 为什么 JsonConvert.DeserializeObject 不使用指定的 JsonConverter?
- json - Microsoft Graph 更新 SharePoint 列表项多选字段
- python - 使用python从XML属性中查找最小和最大元素值
- date - MaterializeCSS 禁用特定日期
- javascript - 一套 ISO8601 时间到现在
- gcc - gcc -fno-trapping-math 有什么作用?
- react-native - React Native中的React Redux Form复选框和下拉字段?