mport UIKit
import CoreData
class ViewController: UITableViewController,UITableViewDataSource {
var context : NSManagedObjectContext?
var fetcheResults = [NSManagedObject]()
@IBOutlet var tabelview: UITableView!
var person1 = [NSManagedObject]()
var company1 = [NSManagedObject]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
///添加数据
seedPerson("波子")
}
//appdelegate 懒加载
lazy var appDelegate:AppDelegate = {
let app = UIApplication.sharedApplication().delegate as! AppDelegate
return app
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(true)
self.hvasertcontext()
}
///查询数据
func hvasertcontext(){
//获取管理上下文
let managedContext = appDelegate.managedObjectContext
//2建立获取的请求
let fetchRqeust = NSFetchRequest(entityName: "Person")
let fetchRqeustcom = NSFetchRequest(entityName: "Company")
//3执行请求
var error: NSError?
self.fetcheResults = managedContext!.executeFetchRequest(fetchRqeust, error: &error) as! [NSManagedObject]!
let fetcheResultsCom = managedContext!.executeFetchRequest(fetchRqeustcom , error: &error) as! [NSManagedObject]!
if self.fetcheResults.count > 0{
println("获取成功 \(self.fetcheResults.count)")
company1 = fetcheResultsCom!
self.tableView.reloadData()
}else{
println("获取失败")
}
}
///删除数据
@IBAction func deleteclice(sender: AnyObject) {
if self.fetcheResults.count > 5{
//3执行请求
var error: NSError?
if (error != nil) {
println("dele error:\(error)")
}else{
for one:NSManagedObject in fetcheResults {
println(one.description)
context?.deleteObject(one)
}
}
if (context?.hasChanges != nil){
context?.save(&error)
self.hvasertcontext()
self.tabelview.reloadData()
}else{
println("context save error:\(error)")
}
}
}
///添加数据
@IBAction func clickAdd(sender: AnyObject) {
let alert = UIAlertController(title: "New name", message: "add a name", preferredStyle: UIAlertControllerStyle.Alert)
var saveation = UIAlertAction(title: "save", style: UIAlertActionStyle.Default) { (action:UIAlertAction!
) -> Void in
let textFied = alert.textFields![0] as! UITextField
//添加数据
self.seedPerson(textFied.text)
}
let cancelltion = UIAlertAction(title: "cancel", style: UIAlertActionStyle.Default) { (action:UIAlertAction!) -> Void in
}
alert.addAction(cancelltion)
alert.addAction(saveation)
alert.addTextFieldWithConfigurationHandler { (textField:UITextField!) -> Void in
}
self.presentViewController(alert, animated: true, completion: nil)
}
///添加数据
func seedPerson(text: String) {
//1获取上下文
let managedContext = appDelegate.managedObjectContext
context = managedContext!
//2 获取实体
let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: managedContext!)
let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) as! Person
//(公司)
let comentity = NSEntityDescription.entityForName("Company", inManagedObjectContext: managedContext!)
let company = NSManagedObject(entity: comentity!, insertIntoManagedObjectContext: managedContext) as! Company
//3 没有类 模型添加数据
// person.setValue(text, forKey: "fistName")
// person.setValue("hello", forKey: "lastname")
//有类 模型 添加数据
company.department = "腾讯"
person.fistName = text
person.lastname = "yusong"
person.company = company
// company.number = 11
company.person = [person]
//4 保存内容
var error : NSError?
if !managedContext!.save(&error)
{
println("无法保存")
}else{
println("保存成功")
self.hvasertcontext()
}
}
}
///ViewController的数据源 UITabelViewDataSource
extension ViewController:UITableViewDataSource{
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return self.fetcheResults.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
if self.fetcheResults.count > 0{
let person = self.fetcheResults[indexPath.row]
let company = company1[0]
cell.textLabel?.text! = person.valueForKey("fistName") as! String
cell.detailTextLabel?.text = company.valueForKey("department") as? String
println("\(cell.textLabel!.text)")
}
return cell
}
}