<Swift>IOS开发Swift语言中应用CoreData之数据存取

本文介绍如何在iOS应用中使用CoreData来持久化表格视图的数据,确保用户输入的内容即使在重启应用后也能保留。通过创建一个Person类并存储name属性,实现数据的保存和加载。

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

Demo是一个tableview,点击右上角按钮弹出一个可输入的alertview。输入之后的内容保存会显示在tableview上。CoreData的使用是将本次启动app之后输入的存在CoreData中,系统清掉app内存之后再次启动app上一次的数据还会显示在列表中。

1.创建一个带有CoreData的项目文件,创建完之后会生成一个hitlist文件。右边的部分类似数据库的一个字段。Person是我自己起得一个类名。name是类里的一个字段,String是类型。




2.storyboard拉一个tableview+cell


3.代码部分

import UIKit
import CoreData

class TableViewController: UITableViewController,UIAlertViewDelegate{
    
    var people = [NSManagedObject]()

    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 viewWillAppear(animated: Bool) {
        /// 取得总代理
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        /// 取得托管对象内容总管
        let manageObjectContext = appDelegate.managedObjectContext
        /// 建立一个获取的请求
        let fetchRequest = NSFetchRequest(entityName:"Person")
        var error: NSError?
        /// 请求操作
        let fetchRequestResults = manageObjectContext!.executeFetchRequest(fetchRequest, error:&error) as! [NSManagedObject]?
        if let results = fetchRequestResults{
            people = results
            self.tableView.reloadData()
        }else{
            println("获取失败")
        }
        
        
    }
    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
        let person = people[indexPath.row]
        cell.textLabel?.text = person.valueForKey("name") as? String
        return cell
    }
    
    
    @IBAction func addAction(sender: UIBarButtonItem) {
        var alertView = UIAlertController(title:"提示", message:"请输入一个新名字", preferredStyle:UIAlertControllerStyle.Alert)
        let saveAction = UIAlertAction(title:"确定", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            let textField = alertView.textFields![0] as! UITextField
            self.saveName(textField.text)
            let indexPath = NSIndexPath(forRow:self.people.count - 1, inSection: 0)
            self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
        }
        let cancleAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default) { (UIAlertAction) -> Void in
            
        }
        alertView.addAction(saveAction)
        alertView.addAction(cancleAction)
        alertView.addTextFieldWithConfigurationHandler{(textField:UITextField!) -> Void in
        }
        self.presentViewController(alertView,animated:true,completion:nil)
    }
    func saveName(text:String){
        /// 取得总代理
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        /// 取得托管对象内容总管
        let manageObjectContext = appDelegate.managedObjectContext
        /// 建立一个entity
        let entiy = NSEntityDescription.entityForName("Person", inManagedObjectContext: manageObjectContext!)
        let person = NSManagedObject(entity:entiy!, insertIntoManagedObjectContext:manageObjectContext!)
        // 保存文本框中的值到person
        person.setValue(text, forKey:"name")
        var error:NSError?
        if  !manageObjectContext!.save(&error){
            println("无法保存")
        }
        // 保存到数组中,刷新UI
        people.append(person)
        
    }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值