2016-12-07 60 views
1

因此,我在保存USERDEFAULTS上的文本域時遇到了問題。我已經設法在我的聯繫人上使用這個方法(因爲您可以在下面看到我的代碼),並且當我嘗試在我的文本字段中保存/加載時沒有工作。你能給我任何建議嗎?由於Userdefault無法正常工作

PBProfile.Swift

class PBProfile { 

    var firstName: String = "" 
    var lastName: String = "" 
    var contacts = [String]() 

    func loadFromDefaults() { 
     let defaults = UserDefaults.standard 
     firstName = defaults.string(forKey: "firstName") ?? "" 
     lastName = defaults.string(forKey: "lastName") ?? "" 
     contacts = defaults.stringArray(forKey: "contacts") ?? [String]() 

    } 

    func saveToDefaults() { 
     let defaults = UserDefaults.standard 
     defaults.set(firstName, forKey: "firstName") 
     defaults.set(lastName, forKey: "lastName") 
     defaults.set(contacts, forKey: "contacts") 
     defaults.synchronize() 
    } 

} 

的AppDelegate

var profile: PBProfile! 
    var location: PBLocation! 

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { 

     FIRApp.configure() 

     profile = PBProfile() 
     profile.loadFromDefaults() 
     profile.saveToDefaults() 

     location = PBLocation() 

     return true 
    } 

} 

Settings.swift

import Foundation 
import ContactsUI 
import Contacts 

class Settings: UIViewController, CNContactPickerDelegate, UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource { 

    //VARIABLES 
    var saveButtonSelected: UIButton! 
    @IBOutlet weak var tableView: UITableView! 
    @IBOutlet weak var firstName: UITextField! 
    @IBOutlet weak var lastName: UITextField! 
    //--- End of Variables -- 

    // -- ViewDidLoad -- 
    override func viewDidLoad() { 
     super.viewDidLoad() 

     self.navigationItem.setHidesBackButton(true, animated: false) 
     self.hideKeyboardWhenTappedAround() 

     firstName.delegate = self 
     lastName.delegate = self 

     tableView.reloadData() 

     firstName.text = app.profile.firstName 
     lastName.text = app.profile.lastName 

     app.profile.loadFromDefaults() 
    } 
    //-- End of ViewDidLoad 

    //Prepare for segue 
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) { 
     app.profile.saveToDefaults() 

    } 


    //MARK -> ADD CONTACTS BUTTON 
    @IBAction func addContactsSelected(_ sender: AnyObject) { 

     _ = CNContactPickerViewController() 
     let contactPicker = CNContactPickerViewController() 
     contactPicker.displayedPropertyKeys = [CNContactPhoneNumbersKey] 
     contactPicker.delegate = self 

     contactPicker.predicateForSelectionOfContact = NSPredicate (value:false) 
     contactPicker.predicateForSelectionOfProperty = NSPredicate(value: true) 
     self.present(contactPicker, animated: true, completion: nil) 
    } 

    //MARK -> WHEN A CONTACT IS SELECTED 
    func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) { 

     let newitem = contactProperty.value as! CNPhoneNumber 
     app.profile.contacts.append(newitem.stringValue) 
     app.profile.saveToDefaults() 
     tableView.reloadData() 

    } 

    //MARK -> TABLEVIEW 
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { 
     return app.profile.contacts.count 

    } 

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { 
     let cell = tableView.dequeueReusableCell(withIdentifier: "Cell") 
     cell!.textLabel?.text = app.profile.contacts[indexPath.row] 
     return cell! 
    } 

    func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) { 
     if editingStyle == .delete { 
      app.profile.contacts.remove(at: indexPath.row) 
      app.profile.saveToDefaults() 
      tableView.deleteRows(at: [indexPath], with: .fade) 
     } else if editingStyle == .insert { 

     } 

    } 
+1

它如何「不工作」?錯誤的數據,崩潰,...? - 您似乎認爲didFinishLaunchingWithOptions在* viewDidLoad之前被稱爲*。這不一定是真實的,請參閱http://stackoverflow.com/questions/32827625/viewcontrollers-viewdidload-called-before-appdelegates-method。 –

回答

0

呦你不存儲這些值。你已經爲這些文本字段設置了委託,並且你應該實現一些UITextFieldDelegate的方法。例如:

func textFieldDidEndEditing(_ textField: UITextField) { 
    if textField == firstName { 
     app.profile.firstName = textField.text 
    } else if textField == lastName { 
     app.profile.lastName = textField.text 
    } 
} 

https://developer.apple.com/reference/uikit/uitextfielddelegate/1619591-textfielddidendediting

請注意,當文本框完成編輯這隻會儲存值(例如,您點擊另一個文本框,並且焦點移動到它)。如果您希望在值更改時存儲值,則可以使用代理的textField(_:shouldChangeCharactersIn:replacementString:)函數或UITextFieldTextDidChange通知(分別爲https://developer.apple.com/reference/uikit/uitextfielddelegate/1619599-textfieldhttps://developer.apple.com/reference/foundation/nsnotification.name/1619640-uitextfieldtextdidchange

+0

感謝它真的幫助! –