Swift 2.2,RealmSwift - 检索不起作用的数据

时间:2016-07-14 00:45:55

标签: ios swift realm

我使用realm作为我的记事本应用程序来存储数组noteTitles,这是一个自定义类Note。该应用程序工作正常,但当它应该保存时,它不会通过。当我重新启动应用程序时,笔记消失了。我将为所有文件提供代码。此外,我希望用户添加注释,我需要每次更新ObjectForPrimaryKey,以便为每个注释创建一个新的id。

注意课程代码:

import Foundation
import RealmSwift

class Note: Object {
   dynamic var title = ""
   var content = ""
   var id = 0

   override class func primaryKey() -> String? {
      print("id generated")
      return "id"
   }
}

ViewController(我在哪里写笔记)代码:

import UIKit
import RealmSwift

var note2 = Note()
var note: Note!

let realm = try! Realm()

class ViewController3: UIViewController, UITextViewDelegate {
   var note: Note!

   @IBOutlet var noteText: UITextView!
   @IBOutlet var noteTitle: UITextField!

   override func viewWillAppear(animated: Bool) {
      super.viewWillAppear(animated)
      noteTitle.text = note.title
      noteText.text = note.content
   }

   override func viewWillDisappear(animated: Bool) {
      super.viewWillDisappear(animated)

      note.title = noteTitle.text!
      note.content = noteText.text
   }

   override func didReceiveMemoryWarning() {
      super.didReceiveMemoryWarning()
      // Dispose of any resources that can be recreated.
   } 

   func textViewDidEndEditing(textView: UITextView) {

      func noteEnded(note2: Note) {

         note2.title = note.title
         note2.content = note.content

         note2.id = note.id

         do {
            try realm.write {
               realm.add(noteTitles, update: true)
               print("added")
            }
          } catch {
            print("There was a problem")
         }
    }

    print("editing ended")

}


    override func viewDidLoad() {
        super.viewDidLoad()

        print(note2.id)
        self.noteText.delegate = self
        // Do any additional setup after loading the view.
    }

    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        self.view.endEditing(true)
        noteTitle.resignFirstResponder()
        noteText.resignFirstResponder()
    }
}

TableViewController(注释列表)代码:

import UIKit
import RealmSwift

var noteTitles:[Note] = []

class TableViewController: UITableViewController {

    // MARK: - Table view data source
    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Incomplete implementation, return the number of sections
        return 1
    }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return noteTitles.count
    }


    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell

        cell.textLabel!.text = noteTitles[indexPath.row].title // error here
        // Configure the cell...
        return cell
    }

    override func viewDidAppear(animated: Bool) {
        tableView.reloadData()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        sleep(2)

        if realm.objectForPrimaryKey(Note.self, key: 0) != nil {
            realm.objectForPrimaryKey(Note.self, key: 0)
        }




        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
        // self.navigationItem.rightBarButtonItem = self.editButtonItem()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

        if editingStyle == UITableViewCellEditingStyle.Delete {
            noteTitles.removeAtIndex(indexPath.row)
            tableView.reloadData()
        }
    }

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier! == "editNote" {
            let noteDetailViewController = segue.destinationViewController as! ViewController3
            let selectedIndexPath = tableView.indexPathForSelectedRow
            noteDetailViewController.note = noteTitles[selectedIndexPath!.row]
        } else if segue.identifier! == "addNote" {
            let note = Note()
            noteTitles.append(note)
            let noteDetailViewController = segue.destinationViewController as! ViewController3
            noteDetailViewController.note = note
        }
    }
}

提前致谢!

1 个答案:

答案 0 :(得分:2)

函数noteEnded不应该在textViewDidEndEditing内,并且不会被调用。 试试这个

func noteEnded(note2: Note) {
    do {
        try realm.write {
            realm.add(note2, update: true)
            print("added")
        }
    } catch {
        print("There was a problem")
    }
}

func textViewDidEndEditing(textView: UITextView) {
    note2.title = note.title
    note2.content = note.content
    note2.id = note.id

    noteEnded(note2)
    print("editing ended")

}

最好有&#34;完成&#34;按钮保存笔记。易于处理输入并保存。