如何将类保存到核心数据中?

时间:2016-05-23 03:11:52

标签: class core-data swift2

我创建了一个名为' webSite'在一个名为' file'

的快速文件中
import UIKit

class webSite
{
    var name: String
    var address: String

    init(Name n: String, Address A: String) {
        name = n
        address = A
    }
    init() {
        name = ""
        address = ""
    }
}



//In another swift file name ViewController I use a button to put value in to that class with a alert controller, and save the value to coreData


class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    @IBOutlet weak var listTable: UITableView!
    @IBOutlet weak var add: UIBarButtonItem!

    var lists = [webSite]()
    var entitys = [NSManagedOBject]()

    override func viewWillAppear(animated: Bool) {
    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName: "Entity")
    do {
        let results =
        try managedContext.executeFetchRequest(fetchRequest)
        entitys = results as! [NSManagedObject]
    } catch let error as NSError {
        print("Could not fetch \(error), \(error.userInfo)")
    }
}

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let currentCell = tableView.dequeueReusableCellWithIdentifier("myCell")!
        let currentList = lists[indexPath.row]
        currentCell.textLabel?.text = currentList.name
        currentCell.detailTextLabel?.text = currentList.address
        return currentCell
    }
    func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if (editingStyle == UITableViewCellEditingStyle.Delete){
            if let table = listTable {
                lists.removeAtIndex(indexPath.row)
                table.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
            }
        }
    }

    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return lists.count
    }
    // save the value into class
    @IBAction func addButton(sender: UIBarButtonItem) {
        let alert = UIAlertController(title: "New Website", message: "Enter New Website", preferredStyle: .Alert)
        alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
            textField.placeholder = "enter web name"
        })
        alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in
            textField.placeholder = "enter web address"
        })
        let textField = alert.textFields![0] as UITextField
        let textField1 = alert.textFields![1] as UITextField
        let finishAction = UIAlertAction(title: "OK", style: .Default) { (finish) -> Void in
            let newWeb = webSite(Name: textField.text!, Address: textField1.text!)
            self.lists.append(newWeb)
            self.save(textField.text!)
            self.listTable.reloadData()
        }
        alert.addAction(finishAction)
        self.presentViewController(alert, animated: true, completion: nil)
    }
}
func save(name:String) {
    let appDelegate =
    UIApplication.sharedApplication().delegate as! AppDelegate
    let managedContext = appDelegate.managedObjectContext
    let entity =  NSEntityDescription.entityForName("Entity",
        inManagedObjectContext:managedContext)
    let webName = NSManagedObject(entity: entity!,
        insertIntoManagedObjectContext: managedContext)
    webName.setValue(name, forKey: "name")
    do {
        try managedContext.save()
        entitys.append(webName)
    } catch let error as NSError  {
        print("Could not save \(error), \(error.userInfo)")
    }
}

我尝试将保存在类中的内容保存到核心数据中,但它要求我的类是NSManagedObject类型

我尝试某种方法将类webSite转换为NSManagedObject,但它根本不起作用。

是否有将此类保存到coreData的方法?

0 个答案:

没有答案