所以,这是我的代码:
ViewController 1:
class ViewSet: UIViewController {
@IBOutlet var Label_1: UILabel!
@IBOutlet var Label_2: UILabel!
@IBOutlet var Text: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "TestingCoreData")
request.returnsObjectsAsFaults = false;
var results: NSArray = moc.executeFetchRequest(request, error: nil)!
if (results.count > 0) {
var res = results[0] as! NSManagedObject
Label_1.text = res.valueForKey("label_1") as? String
Label_2.text = res.valueForKey("label_2") as? String
Text.text = res.valueForKey("text") as? String
} else {
println("No results found")
}
}
}
ViewController 2:
import UIKit
import CoreData
class Label_1: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet var Label_1: UITextField!
@IBAction func addLabel_1(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var label1 = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
label1.setValue("\(Label_1.text)", forKey: "label_1")
moc.save(nil)
println("Object saved")
performSegueWithIdentifier("toLabel2", sender: self)
}
}
ViewController 3:
import UIKit
import CoreData
class Label_2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet var Label_2: UITextField!
@IBAction func add(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var label2 = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
label2.setValue("\(Label_2.text)", forKey: "label_2")
moc.save(nil)
println("Object saved")
performSegueWithIdentifier("toText", sender: self)
}
}
ViewController 4:
import UIKit
import CoreData
class Text: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBOutlet var Text: UITextView!
@IBAction func done(sender: AnyObject) {
var appDel: AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
var moc: NSManagedObjectContext = appDel.managedObjectContext!
var text = NSEntityDescription.insertNewObjectForEntityForName("TestingCoreData", inManagedObjectContext: moc) as! NSManagedObjectContext
text.setValue("\(Text.text)", forKey: "text")
moc.save(nil)
println("Object saved")
navigationController?.popToRootViewControllerAnimated(true)
}
}
我相信代码非常简单。我正在尝试通过CoreData学习,但我似乎无法正常使用它。
当我按下add以转到第3个视图控制器时,它崩溃了:
任何人都可以帮助我吗?我是这个东西的新手!提前致谢