Simple To-Do List using core data in Swift

Note: The steps 1-9 are all simply about setting-up the controllers. The main "core data" begins the next step after. Here's the finish project from step-1 to step-9.

1.) First, for us to have a better view, we have to disable the size classes. Go to the "Main.storyboard" and click the file inspector. Below you can see checkbox for "Use Size Classes" and from there, you can disable it.


2.) Next we have to embed the "ViewController" inside a Navigation Controller. Inside the "Storyboard" click the "ViewController" and go to "Editor" -> "Embed In" -> "Navigation Controller". The "ViewController" must now have a "Navigation Bar". 


3.) Next we have to add a "Bar Button Item" inside the navigation bar. From the "Object Library", grab a "Bar Button Item" and drag it inside the right corner of the navigation bar. From the "Attribute Inspector", change the "Identifier" to add.

4.) Next we have to add another "ViewController". From the "Object Library drag a "ViewController" inside the storyboard. Next we have to connect the first view controller to the second view controller. Click the bar button item of the first view controller and hold the control key and drag it to the second view controller. A pop-up should appear and click "push".



5.) Now with the second view controller, add a bar button item on the left side the of the navigation bar and change the identifier to "cancel". Repeat the same process for the "done" button except that it should be on the right side. Next we have to add a textfield where we can enter our task, drag a textfield inside the view controller just below the navigation bar. Stretch it from the left margin to the right margin.



6.) The second view controller doesn't have a class yet, so go to "File" -> "New" -> "File" and create a new class named "AddViewController". We have to set it as the class of the second view controller, so inside the storyboard click the second view controller and go to "Identity Inspector" and set the class to "AddViewController".

7.) We can now make an action for the "cancel" button. Inside the second view controller, click the "cancel" button and hold down the control key and drag it inside the "AddViewController" class. Fill up the following information similar below:




Repeat the same process for the textfield, name it "txtField_desc".

8.) To be able to go back to the first view controller from the second view controller, we have to pop the second view controller. Inside the function "btn_cancel" that we've just added, add this line of code:

navigationController?.popViewControllerAnimated(true)

9.)  Now with the "done" button, we have to connect it to the first view controller, however we should first have an "anchor point" from the first view controller. So inside the first view controller, add this line of code:


@IBAction func unwindToFirstViewController(segue: UIStoryboardSegue) {
    
}

Now we can connect the second view controller to it, click the "done" button and hold down the control key and drag it to the "exit" button and choose the "unwindToFirstViewController".



If you try to run the app from this point, you can now go back-and-forth from the first view controller to the second view controller.

Again,  here's the set-up from step-1 to step-9

10.) Adding the data. Inside the second view controller class, import "CoreData" and insert this line of codes:


override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        var appDel : AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
        var context : NSManagedObjectContext = appDel.managedObjectContext!
        
        var newTask = NSEntityDescription.insertNewObjectForEntityForName("Task", inManagedObjectContext: context) as NSManagedObject
        
        newTask.setValue(txtField_desc.text as String, forKey: "desc")
        
        var error : NSError?
        
        context.save(&error)
        
        println(newTask)
        println("Object saved")
        
}

11.) Showing the contents of the data. We need a table view where we put a cell, inside the storyboard, drag a table view to the first view controller.

Next we have to add a cell where we can display the task description, drag a single table view cell inside the table view and change its identifier to "cell".

Next we have to connect the table view datasource and delegate to the second view controller, right click the table view and inside the circle next to the data source, hold the control key and drag it to the view controller. Repeat the same process for the delegate.
(See image below)

Next make an outlet of the table view, similar to textfield, just control-drag the table view to its class and name it "tableView"



12.) Inside the first view controller class, import "CoreData". Then we need an array where we can store temporarily our data.

var taskList : [String] = []

Next, we need the table view to display our data so insert this line of codes:

func loadData(){
        println("loading data... please wait...")
        var appDel = UIApplication.sharedApplication().delegate as AppDelegate
        var context = appDel.managedObjectContext
        var error : NSError?
        
        var request = NSFetchRequest(entityName: "Task")
        request.returnsObjectsAsFaults = false
        
        var results : NSArray = context!.executeFetchRequest(request, error: &error)! as NSArray
        if results.count > 0 {
            for res in results{
                taskList += [res.valueForKey("desc") as String]
            }
        }else{
            println("no data loaded")
        }
    }
    
    func numberOfSectionsInTableView(tableView:UITableView!)->Int
    {
        return 1
    }
    
    func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int
    {
        return taskList.count;
    }
    
    func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell!
    {
        let cell:UITableViewCell = UITableViewCell(style:UITableViewCellStyle.Default, reuseIdentifier:"cell")
        cell.textLabel?.text = taskList[indexPath.row]
        
        return cell
    }
    
    func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
    {
        println("You selected cell #\(indexPath.row)!")
    }

Next, for our data to load, we have to invoke it inside the "viewDidLoad" function, inside the function "viewDidLoad" insert this line of code:

 loadData()

Finally, when the user just enter a task, we have to reload the data. So inside the "unwindToFirstViewControlller" function, insert this line of codes:


 taskList.removeAll(keepCapacity: false)
        loadData()
        tableView.reloadData()

Try to run the app and you should have now a working simple to-do app :)
Here's the final code.
Simple To-Do List using core data in Swift Simple To-Do List using core data in Swift Reviewed by Edmond Legaspi on Monday, October 06, 2014 Rating: 5

No comments:

Powered by Blogger.