I want to add a search bar in my tableview which is populated with data from Core Data. Below is parts of code from my TableViewController. How do I begin implementing the searchbar function after placing one on the tableview?
let managedObjectContext =
(UIApplication.sharedApplication().delegate
as! AppDelegate).managedObjectContext
var fetchedLastName = [String]()
var fetchedFirstName = [String]()
var fetchedImage = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "reloadData:",name:"load", object: nil)
let entityDescription =
NSEntityDescription.entityForName("Faculty",
inManagedObjectContext: managedObjectContext)
let request = NSFetchRequest()
request.entity = entityDescription
do{
let objects = try managedObjectContext.executeFetchRequest(request)
let results = objects
if results.count > 0 {
for var i = 0; i < results.count; i += 1{
let match = results[i] as! NSManagedObject
fetchedLastName.append((match.valueForKey("lastname") as? String)!)
fetchedFirstName.append((match.valueForKey("firstname") as? String)!)
let image = match.valueForKey("image") as! NSData
fetchedImage.append(UIImage(data: image)!)
}
} else {
}
}
catch{}
}
func reloadData(notification: NSNotification){
fetchedLastName.removeAll()
fetchedFirstName.removeAll()
fetchedImage.removeAll()
let entityDescription =
NSEntityDescription.entityForName("Faculty",
inManagedObjectContext: managedObjectContext)
let request = NSFetchRequest()
request.entity = entityDescription
do{
let objects = try managedObjectContext.executeFetchRequest(request)
let results = objects
if results.count > 0 {
for var i = 0; i < results.count; i += 1{
let match = results[i] as! NSManagedObject
fetchedLastName.append((match.valueForKey("lastname") as? String)!)
fetchedFirstName.append((match.valueForKey("firstname") as? String)!)
let image = match.valueForKey("image") as! NSData
fetchedImage.append(UIImage(data: image)!)
}
} else {
}
}
catch{}
self.tableView.reloadData()
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("TEACH", forIndexPath: indexPath) as! TEACHTableViewCell
let row = indexPath.row
print(fetchedFirstName)
cell.facultyName.text = fetchedLastName[row] + ", " + fetchedFirstName[row]
cell.facultyImage.image = fetchedImage[row]
return cell
}
}
Try this code all tested:
}