List Application using Core Data [For Beginners]

In this tutorial we are gonna learn how to make list app using core data where you can take any notes keep in your application.

I assume that now you have already setup your Xcode environment and all set to go for a project.

So start a new project

Create a new Xcode project -> Single view application -> Name it as ListApp and make sure you check the Use core data and keep the language as Swift and Device as Universal.

Screen Shot 2559-01-01 at 6.29.22 AM

Click next and save wherever you want and save the project

So all the things are set to start coding!

First go to the Main.storyboard file and delete the UI that you got already and go to the Object library where you can find on right side of the Xcode window and drag and drop the Navigation controller since we are using that for this session.

Now click on your Root View Controller UI and give the class name as we named the ViewController.swift file.(Mine it’s tableViewController) so that you can link your class file with the UI you dragged and dropped recently.

Screen Shot 2016-04-20 at 2.58.08 PM

Then you’ll have to configure some stuff in ListApp.xcdatamodeld file as follows.

Add a new entity(There is a button at the bottom of the window called Add Entity) and give it a name(Mine as ListEntity) and give a attribute with a type (Mine the attribute name as title and type as String).This is something what we got using core data which helps to keep data without flushing by re running the programme.

Screen Shot 2016-04-20 at 3.08.44 PM

Here is my ViewController.swift file and i’ll explain all the methods in brief for a better understanding.


import UIKit
import CoreData

//The class file linked into the Navigation Controller UI
class tableViewController: UITableViewController {

    //This is the array where we store all the inputs
    var listItems = [NSManagedObject]()

    //Default function coming along with a new project.Here we code/call all the fuctions that should work on the beggining of the programme/By just execting the programme
    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.Add , target: self, action: #selector(tableViewController.addItem))
    }

    //Just return the number of items of the listItems
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return listItems.count
    }

    //Here i used a Alert Controller for get the inputs/The configurations of the alert controller
    func addItem() {
        let alertController = UIAlertController(title: "Type the Note", message: "Type..", preferredStyle: .Alert)
        let confirmAction = UIAlertAction(title: "Confirm", style:UIAlertActionStyle.Default , handler: ({
            (_) in
            if let field = alertController.textFields![0] as? UITextField{
                self.saveItem(field.text!)
                self.tableView.reloadData()

            }
        }))
        let cancelAction = UIAlertAction(title: "Cancel", style: UIAlertActionStyle.Cancel, handler: nil)

        alertController.addTextFieldWithConfigurationHandler({
            (textField) in
            textField.placeholder = "Type the Note!!"
        })

        alertController.addAction(confirmAction)
        alertController.addAction(cancelAction)

        self.presentViewController(alertController, animated: true, completion: nil)

    }

    //The inputs are kept in the ListEntity in the attribute of item
    func saveItem(itemToSave: String) {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        let entity = NSEntityDescription.entityForName("ListEntity", inManagedObjectContext: managedContext)
        let item = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext)
        item.setValue(itemToSave, forKey: "item")

        do {
            try managedContext.save()
            listItems.append(item)
        } catch {
            print("Error")
        }
    }

    //For display the inputs taken by the Alert Controller
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        //Cell is the indentifier of the Prototype cells.Make sure you connect that in the first place
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as UITableViewCell
        let item = listItems[indexPath.row]
        cell.textLabel?.text = item.valueForKey("item") as? String
        return cell
    }

    //For remove the notes by clicking on the cells
    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Right)
        managedContext.deleteObject(listItems[indexPath.row])
        listItems.removeAtIndex(indexPath.row)
        self.tableView.reloadData()
    }

    //To keep the files even when delete any notes
    override func viewWillAppear(animated: Bool) {
        let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let managedContext = appDelegate.managedObjectContext
        let fetchRequest = NSFetchRequest(entityName: "ListEntity")

        do {
            let results = try managedContext.executeFetchRequest(fetchRequest)
            listItems = results as! [NSManagedObject]
        } catch {
            print("Error2")
        }
    }
}

Here is the final application build by this tutorial

Screen Shot 2016-04-20 at 3.30.45 PM

Please let me know if you get anything wrong/erros/doubts by following this post.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s