2017-06-22 83 views
1

我正在爲學習目的製作一個預算應用程序,並且有關於在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順序顯示費用。換句話說,我在預算中添加的第一筆開支應該是表格視圖中的第一個元素,依此類推。

回答

1

可能有幾種方法來實現這一點。最直接的方法是使用expense的Ordered關係。在DataModel中編輯

要做到這一點,

  • 打開expense關係屬性。
  • 檢查有序選項

然後budget.expense將不Set,但OrderedSet,你將不再需要將其轉換爲Array,但指數直接訪問它。

+0

美麗!謝謝! – Alberto93

-1

的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 

    } 

}