mardi 28 juillet 2015

I would like to display selected search results from core data in a table view using swift

I have spent a lot of time researching this problem and have not found any help relevant to the matter, so I am hoping this is not a fool's errand. I am developing an app with a core data model where I want the user to perform a search in one screen of the core data, and be able to select which records from the search result are stored in the table view. Every tutorial I have found assumes that I want every record in core data automatically displayed in the table view. At this point I believe I have all of the core data code, and much of the table view code implemented as I would desire. The only thing I want to change is allowing the user to search the core data, and choose which records to display in the table view. The first code snippet I have below is of the table view controller I have to display the core data, and the code following that is the code for the view controller I am using to save, find, and eventually select core data to be displayed. Thank you in advance for your help.

`import Foundation
import UIKit
import CoreData

class PatientViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {

let managedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()


func getFetchedResultController() -> NSFetchedResultsController {
    fetchedResultController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
    return fetchedResultController
}

func taskFetchRequest() -> NSFetchRequest {
    let fetchRequest = NSFetchRequest(entityName: "Patients")
    let sortDescriptor = NSSortDescriptor(key: "lastname", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]
    return fetchRequest
}

var patients = [Patients]()

override func viewDidLoad() {
    super.viewDidLoad()

    fetchedResultController = getFetchedResultController()
    fetchedResultController.delegate = self
    fetchedResultController.performFetch(nil)
}

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    let numberOfSections = fetchedResultController.sections?.count

    return numberOfSections!
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects
    return numberOfRowsInSection!
}

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("MyCellTwo", forIndexPath: indexPath) as! UITableViewCell
    let patient = fetchedResultController.objectAtIndexPath(indexPath) as! Patients

    cell.textLabel?.text = patient.lastname + ", " + patient.firstname

    return cell
}

override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
    let managedObject:NSManagedObject = fetchedResultController.objectAtIndexPath(indexPath) as! NSManagedObject
    managedObjectContext?.deleteObject(managedObject)
    managedObjectContext?.save(nil)
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
    tableView.reloadData()
}
}`

And the second bit of code.

import UIKit
import CoreData

class AddPatientViewController: UIViewController {

@IBOutlet weak var socialSecurityNumber: UITextField!

@IBOutlet weak var lastName: UITextField!

@IBOutlet weak var firstName: UITextField!

@IBOutlet weak var middleInitial: UITextField!

@IBOutlet weak var streetAddress: UITextField!

@IBOutlet weak var apartment: UITextField!

@IBOutlet weak var city: UITextField!

@IBOutlet weak var state: UITextField!

@IBOutlet weak var zipCode: UITextField!

@IBOutlet weak var homePhone: UITextField!

@IBOutlet weak var cellPhone: UITextField!

@IBOutlet weak var workPhone: UITextField!

@IBOutlet weak var mrn: UILabel!

@IBOutlet weak var primaryDiagnosis: UITextField!


@IBAction func savePatient(sender: AnyObject) {
    var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!

    var newPatient = NSEntityDescription.insertNewObjectForEntityForName("Patients", inManagedObjectContext: context) as! NSManagedObject

newPatient.setValue(firstName.text, forKey: "firstname")

    newPatient.setValue(lastName.text, forKey: "lastname")

    newPatient.setValue(socialSecurityNumber.text, forKey: "ssn")

    newPatient.setValue(cellPhone, forKey: "cellphone")

    /*newPatient.setValue(middleInitial.text, forKey: "middileinitial")

    newPatient.setValue(streetAddress, forKey: "streetaddress")

    newPatient.setValue(apartment, forKey: "apartment")

    newPatient.setValue(city, forKey: "city")

    newPatient.setValue(state, forKey: "state")

    newPatient.setValue(zipCode, forKey: "zipcode")

    newPatient.setValue(homePhone, forKey: "homephone")

    newPatient.setValue(workPhone, forKey: "workphone")

    newPatient.setValue(primaryDiagnosis, forKey: "primarydiagnosis")*/


    context.save(nil)

    println(newPatient)
    println("Object Saved.")
}




@IBAction func findPatient(sender: AnyObject) {
    var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    var context:NSManagedObjectContext = appDel.managedObjectContext!

    var request = NSFetchRequest(entityName: "Patients")
    request.returnsObjectsAsFaults = false;
    request.predicate = NSPredicate(format: "lastname = %@", lastName.text)

    var results:NSArray = context.executeFetchRequest(request, error: nil)!

    if(results.count > 0) {
        var res = results[0] as! NSManagedObject
        lastName.text = res.valueForKey("lastname") as! String
        firstName.text = res.valueForKey("firstname") as! String
        socialSecurityNumber.text = res.valueForKey("ssn") as! String
        //for res in results{
        //  println(res)
        //}
    } else {
        println("0 Results Returned...Potential Error")
    }

}

@IBAction func selectPatient(sender: AnyObject) {

    }

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.

}

Aucun commentaire:

Enregistrer un commentaire