我必须做什么,该领域会将日期永久保存?
在我的小测试应用程序中,我使用领域保存用户的文本,但是当我停止应用程序并重新启动它时,数据就会消失。当我只是最小化应用程序或转到另一个视图而不是返回时,数据就在那里。
这是我的TableView,我想在其中显示条目,添加按钮以添加条目。
import UIKit
import RealmSwift
class MediUserlistViewController: UITableViewController {
var userLists = try! Realm().objects(UserListClass).sorted("UserListName")
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return userLists.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("UserListCell", forIndexPath: indexPath)
let userList = userLists[indexPath.row] as UserListClass
cell.textLabel?.text = userList.UserListName
return cell
}
@IBAction func addList(sender: AnyObject) {
let alertController = UIAlertController(title: "Neue Liste", message: "", preferredStyle: UIAlertControllerStyle.Alert)
let saveAction = UIAlertAction(title: "Save", style: UIAlertActionStyle.Default, handler: {
alert -> Void in
let textField = alertController.textFields![0] as UITextField
if(textField.text != ""){
let realm = try! Realm()
let newList = UserListClass ()
newList.UserListName = textField.text!
try! realm.write {
realm.add(newList)
}
self.tableView.reloadData()
}
})
let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Default, handler: {
(action : UIAlertAction!) -> Void in
})
alertController.addTextFieldWithConfigurationHandler { (textField : UITextField!) -> Void in
textField.placeholder = "Name der Liste"
}
alertController.addAction(saveAction)
alertController.addAction(cancelAction)
self.presentViewController(alertController, animated: true, completion: nil)
}
}
这是班级:
import Foundation
import RealmSwift
class UserListClass: Object {
dynamic var UserListName = ""
let Medis = List<MediClass>()
override static func primaryKey() -> String? {
return "UserListName"
}
}