保存/读取CoreData关系Swift 3

问题描述:

我正在为学习目的制作一个预算应用程序,并且有关于在CoreData中存储和获取实体的一些问题。保存/读取CoreData关系Swift 3

我有两个实体“预算”和“费用”。 enter image description here

每个预算都有自己的费用。作为一个例子,我可以有一个'娱乐'的预算,它可以有诸如'保龄球'和'电影'等费用。

我可以创建一个预算并保存它。然后增加费用。

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext 
let expense = Expense(context: context) 
. 
. // Filling out the expense here 
. 
budget?.addToExpense(expense) 
(UIApplication.shared.delegate as! AppDelegate).saveContext() 

我然后检索费的征收,并在TableView中

// Inside cellForRowAt 
let cell = UITableViewCell(style: .default, reuseIdentifier: "cell") 
let myArray = Array((budget?.expense)!) 
cell.textLabel?.text = (myArray[indexPath.row] as! Expense).store 
return cell 

到目前为止好显示商店名称。我的问题是,当我存储费用时,它存储在一个集合中。这意味着当我检索该集合并将它转换为数组时,该顺序是随机的。

我想要的是存储费用,并检索它们,以便我可以在TableView中以FIFO顺序显示费用。换句话说,我在预算中添加的第一笔开支应该是表格视图中的第一个元素,依此类推。

可能有几种方法来实现这一点。最直接的方法是使用expense的Ordered关系。在DataModel中编辑

要做到这一点,

  • 打开expense关系属性。
  • 检查有序选项

然后budget.expense将不Set,但OrderedSet,你将不再需要将其转换为Array,但指数直接访问它。

+0

美丽!谢谢! – Alberto93

的viewController 1: =====================>

进口CoreData

类的ViewController:UIViewController的{

@IBOutlet weak var txt_user: UITextField! 





@IBOutlet weak var txt_password: UITextField! 



var result = NSArray() 



override func viewDidLoad() { 

    super.viewDidLoad() 

    // Do any additional setup after loading the view, typically from a nib. 



    txt_password.isSecureTextEntry = true 

} 







@IBAction func login_action(_ sender: Any) 

{ 

    if(txt_user.text == "" || txt_password.text == "") 

    { 

    let alert = UIAlertController(title: "info", message: "fields are empty", preferredStyle: .alert) 

    let ok = UIAlertAction(title: "OK", style: .default, handler: nil) 

    alert.addAction(ok) 

    self.present(alert, animated: true, completion: nil) 



    } 

    else 

    { 

    self.CheckForUserNameAndPasswordMatch(empName: txt_user.text! , empPwd: txt_password.text!) 

    } 





} 



func CheckForUserNameAndPasswordMatch(empName:String,empPwd:String) 

{ 

    let app = UIApplication.shared.delegate as! AppDelegate 

    let context = app.persistentContainer.viewContext 





    let fetchdata = NSFetchRequest<NSManagedObject>(entityName: "Employee") 

    let predicate = NSPredicate(format: "empName = %@",empName) 

    fetchdata.predicate = predicate 

    do 

    { 

     self.result = try context.fetch(fetchdata as! NSFetchRequest<NSFetchRequestResult>)as NSArray 

     if result.count>0 

     { 

      let objcetEntity = result.firstObject as! Employee 





      if objcetEntity.empName == empName && objcetEntity.empPwd == empPwd 

      { 

       print("Login Successfully") 

       // Entered Username & password matched 

      } 

      else 

      { 

       print("Wrong password/username") 



       //Wrong password/username 

      } 



     } 

    } 

    catch let error as NSError 

    { 

     print("error",error.localizedDescription) 

    } 

} 





@IBAction func unwindToVC1(sender:UIStoryboardSegue) 

{ 

    if sender.source is ViewController2 

    { 

     let secvc = sender.source as! ViewController2 

     txt_password.text = secvc.str1! as String 

    } 



} 

的viewController 2:

=====================>

CLAS小号ViewController2:UIViewController中,UITextFieldDelegate {

@IBOutlet weak var txt_name: UITextField! 



@IBOutlet weak var txt_mail: UITextField! 



@IBOutlet weak var txt_pwd: UITextField! 



@IBOutlet weak var txt_cpwd: UITextField! 



@IBOutlet weak var txt_phone: UITextField! 



@IBOutlet weak var err: UILabel! 



var str1:NSString! 

var str2:NSString! 



//var update:NSManagedObject! 







override func viewDidLoad() { 

    super.viewDidLoad() 



    /*if(update != nil) 

    { 

    txt_name.text = update.value(forKey: "empName") as? String 

    txt_mail.text = update.value(forKey: "empMail") as? String 

    txt_pwd.text = update.value(forKey: "empPwd") as? String 

    txt_cpwd.text = update.value(forKey: "empCpwd") as? String 

    txt_phone.text = update.value(forKey: "empPhone") as? String 

    }*/ 



    txt_pwd.isSecureTextEntry = true 

    txt_cpwd.isSecureTextEntry = true 





} 



override func viewWillAppear(_ animated: Bool) 

{ 

    txt_name.becomeFirstResponder() 

} 









@IBAction func regis_clicked(_ sender: Any) 

{ 



    if(txt_name.text == "" || txt_mail.text == "" || txt_pwd.text == "" || txt_cpwd.text == "" || txt_phone.text == "") 

    { 

     let alert = UIAlertController(title: "information", message: "fields are empty", preferredStyle: .alert) 

     let ok = UIAlertAction(title: "OK", style: .default, handler: 

     { 

      (actionsheet) in 



      if(self.txt_name.text == "") 

      { 

       self.txt_name.becomeFirstResponder() 

      } 

      if(self.txt_mail.text == "") 

      { 

       self.txt_mail.becomeFirstResponder() 

      } 

      if(self.txt_pwd.text == "") 

      { 

       self.txt_pwd.becomeFirstResponder() 

      } 

      if(self.txt_cpwd.text == "") 

      { 

       self.txt_cpwd.becomeFirstResponder() 

      } 

      if(self.txt_phone.text == "") 

      { 

       self.txt_phone.becomeFirstResponder() 

      } 

     }) 



     let cancel = UIAlertAction(title: "cancel", style: .default, handler: nil) 

     alert.addAction(ok) 

     alert.addAction(cancel) 



     self.present(alert, animated: true, completion: nil) 

    } 



    else if(txt_pwd.text != txt_cpwd.text) 

    { 



     let alert1 = UIAlertController(title: "information", message: "password mismatched", preferredStyle: .alert) 

     let ok = UIAlertAction(title: "OK", style: .default, handler:nil) 

     let cancel = UIAlertAction(title: "cancel", style: .default, handler: nil) 

     alert1.addAction(ok) 

     alert1.addAction(cancel) 

     self.present(alert1, animated: true, completion: nil) 

    } 

    else 

    { 



     let app = UIApplication.shared.delegate as! AppDelegate 



     let context = app.persistentContainer.viewContext 



     let newuser = NSEntityDescription.insertNewObject(forEntityName: "Employee", into: context) 

     newuser.setValue(txt_name.text, forKey: "empName") 

     newuser.setValue(txt_mail.text, forKey: "empMail") 

     newuser.setValue(txt_pwd.text, forKey: "empPwd") 

     newuser.setValue(txt_cpwd.text, forKey: "empCpwd") 

     newuser.setValue(txt_phone.text, forKey: "empPhone") 



     do 

     { 

      try context.save() 

     } 

     catch let error as NSError 

     { 

      print("error",error.localizedDescription) 

     } 



    } 

    // self.navigationController?.popViewController(animated: true) 

    performSegue(withIdentifier: "unwind", sender: self) 

} 

覆盖FUNC准备(对于SEGUE:UIStoryboardSegue,发件人:任何)

{ 

    if let newlabel = txt_pwd.text 

    { 

     str1 = newlabel as NSString 

    } 

}