# Systmes > Apple > Dveloppement iOS >  entity et core data ios

## entity_bandit

entity en swift sert  quoi

----------


## entity_bandit

ajouter supprimer modifier avec core data en swift

----------


## karimerri

Entity est l'equivalent de la table dans android

----------


## entity_bandit

On met quoi dans le UIViewController et le uitableview

----------


## entity_bandit

on y met quoi ds adduitableview

----------


## karimerri

class AddViewController: UIViewController {

    @IBOutlet var nameLabel: UITextField!
    @IBOutlet var quantityLabel: UILabel!
    @IBOutlet var quantitySlider: UISlider!
    @IBOutlet var addButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        updateQuantityLabel()

        addButton.isEnabled = false


    }

    func updateQuantityLabel() {
        let currentQuantity = Int(quantitySlider.value)
        quantityLabel.text = "Quantity: \(currentQuantity)"

    }

    private func pressed(sender: UIButton!) {

        let context = CoreDataStack.instance.persistentContainer.viewContext
        let itemEntity = NSEntityDescription.insertNewObject(forEntityName: Item.ENTITY_NAME, into: context) as! Item

        itemEntity.name =  nameLabel.text!
        itemEntity.quantity = Int16(Int(quantitySlider.value))

        CoreDataStack.instance.saveContext()

    }



    //
    //MARK: IBActions
    //

    @IBAction func onNameTextFieldChanged(_ sender: UITextField) {
        addButton.isEnabled = (sender.text?.isEmpty ?? true) == false //disable button when text is empty
    }

    @IBAction func onSliderValueChanged() {
        updateQuantityLabel()
    }

    @IBAction func onCancelButtonTapped() {
        self.presentingViewController?.dismiss(animated: true)
    }


    @IBAction func onAddButtonTapped(_ sender: Any) {
        //addButton.addTarget(self, action: #selector(pressed(_ ::): ), for: .touchUpInside)
         NSLog("pressed!")
        //addButton.addTarget(self, action: #selector(pressed()), for:.touchUpInside)
    }

}

----------


## karimerri

//
//  ListTableViewController.swift
//  WA6-Final
//
//  Created by James Hoffman on 2017-02-21.
//  Copyright  2017 PAM. All rights reserved.
//

import Foundation
import UIKit
import CoreData

class ListTableViewController: UITableViewController, UIPopoverPresentationControllerDelegate,
NSFetchedResultsControllerDelegate {


    private var fetchedResultsController: NSFetchedResultsController<Item>!


    override func viewDidLoad() {
        super.viewDidLoad()


        let context = CoreDataStack.instance.persistentContainer.viewContext

        let request = NSFetchRequest<Item>(entityName: Item.ENTITY_NAME)

        do {
            let results = try context.fetch(request)

            if (results.count == 0) {

                CoreDataStack.instance.saveContext()
            }

            request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
            fetchedResultsController = NSFetchedResultsController(fetchRequest: request,
                                                                  managedObjectContext: context,
                                                                  sectionNameKeyPath: nil,
                                                                  cacheName: nil)
            fetchedResultsController.delegate = self

            try fetchedResultsController.performFetch()
        } catch {
            print("Fetch error")
        }
    }



    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if let sections = fetchedResultsController.sections {
            return sections[section].numberOfObjects
        } else {
            return fetchedResultsController.fetchedObjects!.count
        }
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "item_cell_identifier", for: indexPath)

        let item = fetchedResultsController.object(at: indexPath)
        cell.textLabel?.text = item.name
        cell.detailTextLabel?.text = "Quantity: \(item.quantity)"


        return cell
    }


    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        //automatically deselect row
        tableView.deselectRow(at: indexPath, animated: true)
    }

    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if (segue.identifier == "add_popover_segue") {
            if let dest = segue.destination as? AddViewController {
                dest.modalPresentationStyle = .popover
                dest.popoverPresentationController?.delegate = self
            }
        }
    }


    override func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {

        let deleteAction = UITableViewRowAction(style: .destructive, title: "delete") { (_ , indexPath) in

            let alert = UIAlertController(title: "Delete item", message: "Are you sure you want to delete this item?", preferredStyle: .alert)

            let cancelAction = UIAlertAction(title: "Cancel", style: .cancel, handler: { _ in
                tableView.isEditing = false
            })
            alert.addAction(cancelAction)

            let deleteAction = UIAlertAction(title: "Yes!", style: .destructive, handler: { _ in
                let item = self.fetchedResultsController.object(at: indexPath)
                let context = CoreDataStack.instance.persistentContainer.viewContext

                context.delete(item)
                CoreDataStack.instance.saveContext()

                tableView.isEditing = false
            })
            alert.addAction(deleteAction)

            self.present(alert, animated: true)
        }

        return [deleteAction]
    }


    //
    //MARK: UIPopoverPresentationControllerDelegate
    //

    func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
        return .none
    }

    func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        tableView.reloadData()
    }

}

----------


## karimerri

//
//  ViewController.swift
//  WA6-Final
//
//  Created by James Hoffman on 2017-02-21.
//  Copyright  2017 PAM. All rights reserved.
//

import UIKit
import CoreData

class AddViewController: UIViewController {

    @IBOutlet var nameLabel: UITextField!
    @IBOutlet var quantityLabel: UILabel!
    @IBOutlet var quantitySlider: UISlider!
    @IBOutlet var addButton: UIButton!

    override func viewDidLoad() {
        super.viewDidLoad()

        updateQuantityLabel()

        addButton.isEnabled = false


    }

    func updateQuantityLabel() {
        let currentQuantity = Int(quantitySlider.value)
        quantityLabel.text = "Quantity: \(currentQuantity)"

    }

    private func pressed() {

        let context = CoreDataStack.instance.persistentContainer.viewContext
        let itemEntity = NSEntityDescription.insertNewObject(forEntityName: Item.ENTITY_NAME, into: context) as! Item

        itemEntity.name =  nameLabel.text!
        itemEntity.quantity = Int16(Int(quantitySlider.value))

        CoreDataStack.instance.saveContext()

    }



    //
    //MARK: IBActions
    //

    @IBAction func onNameTextFieldChanged(_ sender: UITextField) {
        addButton.isEnabled = (sender.text?.isEmpty ?? true) == false //disable button when text is empty
    }

    @IBAction func onSliderValueChanged() {
        updateQuantityLabel()
    }

    @IBAction func onCancelButtonTapped() {
        self.presentingViewController?.dismiss(animated: true)
    }


    @IBAction func onAddButtonTapped(_ sender: Any) {
        pressed()
        self.presentingViewController?.dismiss(animated: true)

         NSLog("pressed!")

    }

}

----------


## entity_bandit

Qulequ'un aurait il un tuto expliquant le fetchRequest
Surtout pour utiliser dans le CoreData

----------

