iOS 之 Core Data实践 1

1,新建一个项目,勾选core data

2,删除默认的viewcontroller,新添加一个table view controller,并给其创建一个类TableViewController:UITableViewController

3,给table view controller嵌入一个Navigation Controller

4,在table view controller的导航栏右上角嵌入一个bar button,system item属性设置为add

5,拖线给add按键增加一个“addName”事件

6,在TableViewController中新建一个数组保存数据:

  var names = [String]()

7,给TableView中的cell的identyfier属性设为“cell”

8,viewDidLoad中,设置页面title

  title = "姓名列表"

9,配置tableview

  numberOfSectionsInTableView:

  return 1

  numberOfRowsInSection:

  return userName.count

  cellForRowAtIndexPath:

      let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
      cell.textLabel?.text = names[indexPath.row]
      return cell

10,编写add的方法,添加数据

    @IBAction func addName(sender: AnyObject) {
        let alert = UIAlertController(title: "添加新姓名", message: "请输入一个姓名", preferredStyle: UIAlertControllerStyle.Alert)
        let saveAction = UIAlertAction(title: "保存", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            let textfiled = alert.textFields![0] as UITextField
            self.names.append(textfiled.text!)
            let indexPath = NSIndexPath(forRow: (self.names.count-1), inSection: 0)
            self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic)
            print("存入了一条数据")
        }
        let cancelAction = UIAlertAction(title: "取消", style: UIAlertActionStyle.Default) { (action:UIAlertAction) -> Void in
            print("用户取消了输入")
        }
        alert.addAction(saveAction)
        alert.addAction(cancelAction)
        alert.addTextFieldWithConfigurationHandler { (textfield:UITextField) -> Void in
        }
        self.presentViewController(alert,animated:true,completion:nil)
    }

  到这里,可以添加数据,但数据不能永久保存

  

 

posted on 2015-12-17 10:57  罗小夕  阅读(147)  评论(0编辑  收藏  举报

导航