swift开发之coredata数据存取(1)

本文介绍了一个使用Swift语言实现的花名册应用,包括添加姓名、保存到Core Data、显示列表和基本的增删改查操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//
//  ListViewController.swift
//  花名册
//
//  Created by LYJ on 15/1/26.
//  Copyright (c) 2015年 nbut. All rights reserved.
//


import UIKit
import CoreData


class ListViewController: UITableViewController {


    @IBAction func addName(sender: AnyObject) {
        
        var 输入框 = UIAlertController(title: "添加姓名", message: "请输入一个名字", preferredStyle: UIAlertControllerStyle.Alert)
        
        let 保存 = UIAlertAction(title: "保存", style: UIAlertActionStyle.Default) { (action: UIAlertAction!) -> Void in
            
            let 文本 = 输入框.textFields![0] as UITextField
            //self.p.append(文本.text)
            
            self.保存姓名(文本.text)
            //self.tableView.reloadData()
            let indexPaths = NSIndexPath(forRow: (self.people.count - 1), inSection: 0)
            self.tableView.insertRowsAtIndexPaths( [indexPaths], withRowAnimation: UITableViewRowAnimation.Automatic)
            
            
        }
        
        let 取消 = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default, handler: nil)
        
        输入框.addAction(保存)
        输入框.addAction(取消)
        
        输入框.addTextFieldWithConfigurationHandler { (textfield: UITextField!) -> Void in
            
        }
        
        self.presentViewController(输入框, animated: true, completion: nil)
    }
    func 保存姓名(text : String){
        //保存数据5个步骤
        //1.取得总代理和托管对象内容总管
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let manageObjectContext = appDelegate.managedObjectContext
        
        //2.建立一个entity
        let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext: manageObjectContext!)
        let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: manageObjectContext!)
        
        //3.保存文本框中的值到 coredata中的Person
        person.setValue(text, forKey: "name")
        
        //4.保存entity到托管对象内容总管中
        var error : NSError?
        if !manageObjectContext!.save(&error){
            println("无法保存\(error),\(error!.userInfo)")
        }
        
        //5.保存到数组中更新UI
        people.append(person)
    }
    
    
    
    //var 姓名数组 = [String]()
    
    var people = [NSManagedObject]()
    
    
    override func viewDidAppear(animated: Bool) {
        //获取数据3个步骤
        //1.取得总代理和托管对象内容总管
        let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let manageObjectContext = appDelegate.managedObjectContext
        
        //2.建立获取请求
        let fetchRequest = NSFetchRequest(entityName: "Person")
        
        //3.执行请求
        var error: NSError?
        let fetchResults = manageObjectContext?.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
        if let result = fetchResults {
            people  = result
            self.tableView.reloadData()
        }else{
            println("无法获取\(error),\(error?.userInfo)")
        }
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()


        
        // 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.
    }


    // MARK: - Table view data source


    override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        // #warning Potentially incomplete method implementation.
        // Return the number of sections.
        return 1
    }


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


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


        // Configure the cell...
        let person = people[indexPath.row]
        
        cell.textLabel?.text = person.valueForKey("name") as String?


        return cell
    }
    


    /*
    // Override to support conditional editing of the table view.
    override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the specified item to be editable.
        return true
    }
    */


    /*
    // Override to support editing the table view.
    override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
        if editingStyle == .Delete {
            // Delete the row from the data source
            tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
        } else if editingStyle == .Insert {
            // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
        }    
    }
    */


    /*
    // Override to support rearranging the table view.
    override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {


    }
    */


    /*
    // Override to support conditional rearranging of the table view.
    override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        // Return NO if you do not want the item to be re-orderable.
        return true
    }
    */


    /*
    // MARK: - Navigation


    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */


}


欢迎转载,转载请注明出处http://blog.youkuaiyun.com/colinasd

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值