ios, swift, core data + multiple tables - ios

I'm very new to ios and swift. On a single view, how can I send two different fetch requests to two different table views? I have a class level fetchReq function that uses NSPredicate to take a parameter and give me the varied results that I want. The only place that knows which table is which is the tablView func, but it looks like the decision about which data to load gets made immediately on viewDidLoad. Could some kind soul help me restructure the core data code so that I get a different fetch request for each table?
import UIKit
import CoreData
class CustomTableViewCell : UITableViewCell {
#IBOutlet var l1: UILabel?
#IBOutlet var l2: UILabel?
func loadItem(#number: String, name: String) {
l1!.text = number
l2!.text = name
}
}
class ViewController: UIViewController, UITableViewDelegate, NSFetchedResultsControllerDelegate, UITableViewDataSource {
#IBOutlet var tableView1: UITableView!
//this is my second table - Ive connected it in the IB to this VC. both tables work, but are identical
#IBOutlet var tableView2: UITableView!
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()
//the filtering happens inside this function. it gets called via didLoad, not cellsForRows
func playerFetchRequest(playerType: String) -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Players")
let sortDescriptor = NSSortDescriptor(key: "number", ascending: true)
let filter = NSPredicate(format: "%K = %#", "type", playerType)
fetchRequest.sortDescriptors = [sortDescriptor]
fetchRequest.predicate = filter
return fetchRequest
}
func getFetchedResultController() -> NSFetchedResultsController {
fetchedResultController = NSFetchedResultsController(fetchRequest: playerFetchRequest(playerType), managedObjectContext:managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultController
}
//remember: to create a table with multiple sections just implement the numberOfSectionsInTableView(_:) method
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let numberOfRowsInSection = fetchedResultController.sections?[section].numberOfObjects
{return numberOfRowsInSection} else {return 0}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if (tableView == tableView2) {
var playerType = "Forward"
var cell:CustomTableViewCell = self.tableView1.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
let player = fetchedResultController.objectAtIndexPath(indexPath) as DataModel
cell.l2?.text = player.lastName + ", " + player.firstName
cell.l1?.text = player.number
println(tableView)
return cell
}
else {
var playerType = "Defender"
var cell:CustomTableViewCell = self.tableView2.dequeueReusableCellWithIdentifier("customCell") as CustomTableViewCell
let player = fetchedResultController.objectAtIndexPath(indexPath) as DataModel
cell.l2?.text = player.lastName + ", " + player.firstName
cell.l1?.text = player.number
println(tableView)
return cell
}
}
func tableView(tableView: UITableView!, didDeselectRowAtIndexPath indexPath: NSIndexPath!) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
println("You selected cell #\(indexPath.row)!")
}
override func viewDidLoad() {
var nib = UINib(nibName: "CustomTableViewCell", bundle: nil)
tableView1.registerNib(nib, forCellReuseIdentifier: "customCell")
tableView2.registerNib(nib, forCellReuseIdentifier: "customCell")
fetchedResultController = getFetchedResultController()
fetchedResultController.delegate = self
fetchedResultController.performFetch(nil)
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func controllerDidChangeContent(controller: NSFetchedResultsController!) {
tableView1.reloadData()
tableView2.reloadData()
}
}

You need 2 fetchedResultsControllers with the two different fetch requests for each table. If your tables delegates and datasources are both this view controller, you'll need to switch and provide the corresponding content... for example:
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (tableView == tableView2)
{
return fetchedResultController2.sections?[section].numberOfObjects
}
else
{
return fetchedResultController.sections?[section].numberOfObjects
}
}
Another option would be to create 2 custom MYTableViewDataSource objects and set the datasource for each table view to that... It might make it more obvious when you've got unexpected behaviour and make the data easier to control.

Just establish two separate NSFetchedResultsController objects, one for each table:
var forwardFetchedResultController: NSFetchedResultsController
var defenderFetchedResultController: NSFetchedResultsController
then in viewDidLoad create them with different NSFetchRequests for each. And in your tableView functions, use the correct fetched results controller for the correct table.

Related

Populate the data saved on core data on a tableView

The code of my first UIViewController looks like this and basically I want to save the data whatever I type on the UITextField and retrieve it and populate on a UITableView. code as below. (I think my issue is in the cellForRow method)
import UIKit
import CoreData
class ViewController: UIViewController {
#IBOutlet weak var textField1: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#IBAction func nxtbuttonpressed(_ sender: AnyObject) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
//Lets save data
let newUser = NSEntityDescription.insertNewObject(forEntityName: "Expenses", into: context)
newUser.setValue(textField1.text, forKey: "expenseName")
do {
try context.save ()
print("data saved successfully")
}catch{
print("There was an error")
}
performSegue(withIdentifier: "ShowNxtVC", sender: nil)
}
}
This is where I retrieve the data that I saved in the above VC (as the code bellow). However even though I can print all the data on the console, only the last data item I saved will populate to the UITableViewCell. How can i overcome this as to populate all the data that I've saved before instead the one that i saved last.
import UIKit
import CoreData
class TableViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var tableView: UITableView!
var myArray : Array? = []
override func viewDidLoad() {
super.viewDidLoad()
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let request = NSFetchRequest <NSFetchRequestResult> (entityName: "Expenses")
request.returnsObjectsAsFaults = false
do {
let results = try context.fetch(request)
// check data existance
if results.count>0 {
print(results.count)
for resultGot in results as! [NSManagedObject]{
if let expName = resultGot.value(forKey:"expenseName") as? String{
myArray = [expName]
print("my array is : \(myArray)")
}
}
}
}catch{
print("No Data to load")
}
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print(myArray?.count)
return myArray!.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = UITableViewCell ()
cell.textLabel?.text = myArray? [indexPath.row] as! String?
return cell
}
}
first off all you have to change this:
myArray = [newValue] because that resets your array with just one value every time it finds a new expense in core data.
var array = [String]()
array = ["hello"]
array = ["joe"]
print(array)
// returns: ["joe"]
use:
myArray.append(newExpense)
and you get:
var array2 = [String]()
array2.append("hello")
array2.append("joe")
print(array2)
// returns: ["hello", "joe"]
After the FOR loop you add:
tableView.reloadData()
Now you should be up and running
There is another thing you should do:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "ExpCell", for: indexPath)
cell.textLabel?.text = myArray?[indexPath.row] as! String
return cell
}
In your Storyboard you need to put ExpCell as reuse identifier into the TableViewCell. The dequeReusableCell command loads only the cells you can see on your device and reuses those cells after you scrolled them out of sight. This way your app uses much less memory and will be faster.
update table view with data, after myArray = [expName] use
DispatchQueue.main.async { [unowned self] in
self.tableView.reloadData()
}
change the tableview cell for row at index path function that will solve your problem
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier identifier: String,
for indexPath: IndexPath)
if(!cell){
cell = tableView.register(tableViewCellClass,forCellReuseIdentifier identifier: String)
}
return cell
}

How to update the data from the searchResultsController (UISearchController)

So I am using a searchResultsController, which takes an array of Strings, and shows them in a tableview (It's an autocomplete list). When the user presses the 'Search' button on the keyboard, and the entered String is not yet in my Tableview, I want to add it, and update the tableview accordingly.
The issue is that once I added a String to the array, and make a new search, the array isn't updated with the new value!
Here is my code:
In my ViewDidLoad() on the Overview.swift class
class Overview: UIViewController,UISearchControllerDelegate,UISearchBarDelegate,UICollectionViewDelegate,UICollectionViewDataSource {
var mySearchController : UISearchController!
var mySearchBar : UISearchBar!
override func viewDidLoad() {
super.viewDidLoad()
let src = SearchResultsController(data: convertObjectsToArray())
// instantiate a search controller and keep it alive
mySearchController = UISearchController(searchResultsController: src)
mySearchController.searchResultsUpdater = src
mySearchBar = mySearchController.searchBar
//set delegates
mySearchBar.delegate = self
mySearchController.delegate = self
}
This is the data function, used for the UISearchController
func convertObjectsToArray() -> [String] {
//open realm and map al the objects
let realm = try! Realm()
let getAutoCompleteItems = realm.objects(AutoComplete).map({$0})
...
return convertArrayStrings // returns [String] with all words
}
So when the user pressed the search button on the keyboard, I save that word to my database.
Now I need to put the updated version of convertObjectsToArray() in my searchResultsController, but I haven't found out how to do this. All help is welcome
And last, but not least, my SearchResultsController class, which is used in the viewDidLoad of my Overview.swift class.
class SearchResultsController : UITableViewController {
var originalData : [String]
var filteredData = [String]()
init(data:[String]) {
self.originalData = data
super.init(nibName: nil, bundle: nil)
}
required init(coder: NSCoder) {
fatalError("NSCoding not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.filteredData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel!.text = self.filteredData[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
clickedInfo = filteredData[indexPath.row]
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 1
}
}
For the filtering of my words in the tableview (when user types something, only matching Strings are shown), I use the following extension.
extension SearchResultsController : UISearchResultsUpdating {
func updateSearchResultsForSearchController(searchController: UISearchController) {
let sb = searchController.searchBar
let target = sb.text!
self.filteredData = self.originalData.filter {
s in
let options = NSStringCompareOptions.CaseInsensitiveSearch
let found = s.rangeOfString(target, options: options)
return (found != nil)
}
self.tableView.reloadData()
}
You can use the search controller's update function for that I think:
func updateSearchResultsForSearchController(searchController: UISearchController) {
convertObjectsToArray()
self.tableView.reloadData()
}

UITableview Section?

I am trying to have two sections in my tableView. I would like items to add to section 0 and then be able to select a row to move it from section 0 to section 1. So far, I have the items added to section 0, but the data doesn't load when it dismisses the second viewController. I have to change views (hit the add button the back button) and it finally shows up (still haven't figured that out). I know moving the row across sections must be done through the arrays and the didSelectRow method, but it's throwing me for a loop (especially with the coreData). Do I create a second array for the section 1 items? The TableView data is inputted from a second ViewController and managed by the NSFetchedResultsController for the Entity "SList". I have created an attribute for the "slcross" under "SList" (also included the input "slitem", "sldesc", "slqty", and "slprice" but have no idea how to go about getting it from section 0 to section 1. Or, do I need to create a second entity for the crossed off items? Sorry, I am in slightly over my head...
class ShoppingList: UIViewController, NSFetchedResultsControllerDelegate, UITableViewDataSource, UITableViewDelegate {
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
var frc : NSFetchedResultsController = NSFetchedResultsController()
func itemFetchRequest() -> NSFetchRequest{
let fetchRequest = NSFetchRequest(entityName: "SList")
let primarySortDescription = NSSortDescriptor(key: "slcross", ascending: true)
let secondarySortDescription = NSSortDescriptor(key: "slitem", ascending: true)
fetchRequest.sortDescriptors = [primarySortDescription, secondarySortDescription]
return fetchRequest
}
func getFetchRequetController() ->NSFetchedResultsController{
frc = NSFetchedResultsController(fetchRequest: itemFetchRequest(), managedObjectContext: moc, sectionNameKeyPath: "slcross", cacheName: nil)
return frc
}
#IBOutlet weak var tableView: UITableView!
#IBAction func AddNew(sender: AnyObject) {
frc = getFetchRequetController()
frc.delegate = self
do {
try frc.performFetch()
} catch _ {
print("Failed to perform inital fetch.")
return
}
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
frc = getFetchRequetController()
frc.delegate = self
do {
try frc.performFetch()
} catch _ {
print("Failed to perform inital fetch.")
return
}
self.tableView.reloadData()
//TableView Background Color
self.tableView.backgroundColor = UIColor.clearColor()
self.tableView.separatorColor = UIColor.blackColor()
tableView.reloadData()
override func viewDidDisappear(animated: Bool) {
frc = getFetchRequetController()
frc.delegate = self
do {
try frc.performFetch()
} catch _ {
print("Failed to perform inital fetch.")
return
}
self.tableView.reloadData()
}
//tableView Data
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
let managedObject:NSManagedObject = frc.objectAtIndexPath(indexPath) as! NSManagedObject
moc.deleteObject(managedObject)
do {
try moc.save()
} catch _ {
print("Failed to save.")
return
}
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
let numberOfSections = frc.sections?.count
return numberOfSections!
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?{
let sectionHeader = "Items - #\(frc.sections![section].numberOfObjects)"
let sectionHeader1 = "Crossed Off Items - #\(frc.sections![section].numberOfObjects)"
if (section == 0) {
return sectionHeader
}
if (section == 1){
return sectionHeader1
}else{
return nil
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRowsInSection = frc.sections?[section].numberOfObjects
return numberOfRowsInSection!
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let items = frc.objectAtIndexPath(indexPath) as! SList
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.text = "\(items.slitem!) - Qty: \(items.slqty!)"
cell.textLabel?.font = UIFont.systemFontOfSize(23)
return cell
}
//end tablevViewData*/
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
tableView.reloadData()
}
//segue to add/edit
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "edit" {
let cell = sender as! UITableViewCell
let indexPath = tableView.indexPathForCell(cell)
let SListController:SLEdit = segue.destinationViewController as! SLEdit
let items:SList = frc.objectAtIndexPath(indexPath!) as! SList
SListController.item = items
}
}
}
second ViewController
class SLEdit: UIViewController {
let moc = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
#IBOutlet weak var slitem: UITextField!
#IBOutlet weak var sldesc: UITextField!
#IBOutlet weak var slqty: UITextField!
#IBOutlet weak var slprice: UITextField!
var item: SList? = nil
override func viewDidLoad() {
super.viewDidLoad()
if item != nil{
slitem.text = item?.slitem
sldesc.text = item?.sldesc
slqty.text = item?.slqty
slprice.text = item?.slprice
}
// "x" Delete Feature
self.slitem.clearButtonMode = UITextFieldViewMode.WhileEditing
self.sldesc.clearButtonMode = UITextFieldViewMode.WhileEditing
self.slqty.clearButtonMode = UITextFieldViewMode.WhileEditing
self.slprice.clearButtonMode = UITextFieldViewMode.WhileEditing
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func dismissVC() {
navigationController?.popViewControllerAnimated(true)
}
// Dispose of any resources that can be recreated.
#IBAction func saveButton(sender: AnyObject) {
if item != nil {
edititems()
} else {
createitems()
}
dismissVC()
}
func createitems() {
let entityDescription = NSEntityDescription.entityForName("SList", inManagedObjectContext: moc)
let item = SList(entity: entityDescription!, insertIntoManagedObjectContext: moc)
item.slitem = slitem.text
item.sldesc = sldesc.text
item.slqty = slqty.text
item.slprice = slprice.text
if slitem.text == nil{
createitems()
}else{
edititems()
}
do {
try moc.save()
} catch _ {
return
}
}
func edititems() {
item?.slitem = slitem.text!
item?.sldesc = sldesc.text!
item?.slqty = slqty.text!
item?.slprice = slprice.text!
do {
try moc.save()
} catch {
return
}
}
}
I am just learning and teaching myself so if you could show me and explain it so I could understand I would appreciate it!
... the data doesn't load when it dismisses the second viewController ...
I can't immediately see why that's the case. I suggest using breakpoints and/or print() to try to debug it. I would expect the table view to be automatically updated by the FRC in the controllerDidChangeContent delegate method, so start by putting
print("Controller didChangeContent reloaded the tableView")
in that method and see whether it appears in the log after you create/edit an item. Likewise for the AddNew IBAction method and viewDidDisappear.
... Do I create a second array for the section 1 items...
No need. The FRC should manage the sections and items for you: assuming slcross is a Boolean attribute, the FRC will analyse the SLItem objects and allocate them correctly to section 0 if slcross is false, and section 1 if it is true. (The indexPath used to "lookup" objects in the FRC, eg
let items = frc.objectAtIndexPath(indexPath) as! SList
comprises both the section and the row).
...how to go about getting it from section 0 to section 1...
To ensure that the items are correctly allocated when first created, add:
item.slcross = false
to the createItems() method. To move an item from section 0 to section 1, change this value to true - as you say, didSelectRowAtIndexPath is probably a good place to do this:
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let items = frc.objectAtIndexPath(indexPath) as! SList
items.slcross = true
}
...do I need to create a second entity for the crossed off items?
No need, the FRC should do the necessary.

Retrieve Random String from Core Data in Swift

I've searched for this answer but have come up empty handed. For some reason I'm drawing a blank on how to retrieve a random entry from a Core Data String attribute. I have everything else working - create, update, delete... but can't seem to get a handle on getting a random entry from the stack.
Feeling confused on this. Here is my code from my table view controller that mostly manages the core data.
import UIKit
import CoreData
class TaskManagerViewController: UITableViewController, NSFetchedResultsControllerDelegate {
let managedObjectContext = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext
var fetchedResultController: NSFetchedResultsController = NSFetchedResultsController()
override func viewDidLoad() {
super.viewDidLoad()
fetchedResultController = getFetchedResultController()
fetchedResultController.delegate = self
fetchedResultController.performFetch(nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == "edit" {
let cell = sender as UITableViewCell
let indexPath = tableView.indexPathForCell(cell)
let taskController:TaskDetailViewController = segue.destinationViewController as TaskDetailViewController
let task:Tasks = fetchedResultController.objectAtIndexPath(indexPath!) as Tasks
taskController.task = task
}
}
func getFetchedResultController() -> NSFetchedResultsController {
fetchedResultController = NSFetchedResultsController(fetchRequest: taskFetchRequest(), managedObjectContext: managedObjectContext!, sectionNameKeyPath: nil, cacheName: nil)
return fetchedResultController
}
func taskFetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Tasks")
let sortDescriptor = NSSortDescriptor(key: "desc", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
return fetchRequest
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
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("Cell", forIndexPath: indexPath) as UITableViewCell
let task = fetchedResultController.objectAtIndexPath(indexPath) as Tasks
cell.textLabel.text = task.desc
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()
}
}
func randomTask() -> Tasks {
let count=UInt32(fetchedResultController.fetchedObjects!.count)
let index=Int(arc4random_uniform(count))
return fetchedResultsController.fetchedObjects[index] as Tasks
}
This is the code that ultimately delivered the results I was looking for:
(I'm new at stack overflow so not sure how to select correct answer here.)
func randomTask() -> Tasks {
let count = UInt32(fetchedResultController.fetchedObjects!.count)
let index = Int(arc4random_uniform(count))
var results = fetchedResultController.fetchedObjects![index] as Tasks
answerLabel.text = results.valueForKey("desc") as NSString
return results
}

UITableView not populated. Item size is 2

I'm in the process of making a small app for myself to try out Swift and so forth, and I think I am missing something simple here.
So in my controller, i have the proper delegates and methods to support it:
class MatchListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource
I then setup & populate the table
override func viewDidLoad() {
super.viewDidLoad()
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
loadResults()
}
func loadResults() {
let delegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext! = delegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Series")
var error:NSError? = nil
results = context.executeFetchRequest(fetchRequest, error: &error) as NSArray
}
In Storyboard, the UITableView is connected to my IBOutlet, and refers to MatchListViewController as its delegate.
#IBOutlet var tableView: UITableView!
I setup the cellForRowAtIndexPath method as such:
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell") as UITableViewCell
if let row = indexPath?.row {
let object = results.objectAtIndex(row) as NSObject
if (object != nil) {
let teamOneName = object.valueForKey("team_one") as NSString
let teamTwoName = object.valueForKey("team_two") as NSString
cell.textLabel!.text = "\(teamOneName) vs \(teamTwoName)"
}
}
return cell
}
Any ideas on what I may be missing here?

Resources