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

来源:互联网 发布:淘宝dw旗舰店是真是假 编辑:程序博客网 时间:2024/05/29 18:44

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

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




2.storyboard拉一个tableview+cell


3.代码部分

import UIKitimport CoreDataclass 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)            }




0 0
原创粉丝点击