-1

I am getting this wrapping error when I implement my fetched managed object core data code. I realise that it may be due to needing data in my managedObjectContext but that throws a lot more errors in my code.. any other ideas??

class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, NSFetchedResultsControllerDelegate {

let ReuseIdentifierToDoCell = "ToDoCell"

@IBOutlet weak var tableView: UITableView!

var managedObjectContext: NSManagedObjectContext!

lazy var fetchedResultsController: NSFetchedResultsController = {
    // Initialize Fetch Request
    let fetchRequest = NSFetchRequest(entityName: "Item")

    // Add Sort Descriptors
    let sortDescriptor = NSSortDescriptor(key: "createdAt", ascending: true)
    fetchRequest.sortDescriptors = [sortDescriptor]

    // Initialize Fetched Results Controller
    let fetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext, sectionNameKeyPath: nil, cacheName: nil)

    // Configure Fetched Results Controller
    fetchedResultsController.delegate = self

    return fetchedResultsController
}()
Leanneheal
  • 1
  • 1
  • 7
  • 1
    Is there a good reason why your `managedObjectContext` is an implicitly unwrapped optional? (Just "It silences errors in my code" *isn't* a good reason) Where do you assign a value to it? You should only ever use implicitly unwrapped optionals with a great deal of care. My [answer here](http://stackoverflow.com/a/36360605/2976878) might be useful for helping you deal with optionals safely. – Hamish Apr 09 '16 at 10:59
  • at what line in your code did you get that error? – Ahmed Onawale Apr 09 '16 at 10:59
  • at the let fetchedResultsController = NSFetchedController – Leanneheal Apr 09 '16 at 11:02
  • @Leanneheal That means your `managedObjectContext` is nil when you come to access it in your `fetchedResultsController` initialisation. You need to make sure it has a value before you access your `fetchedResultsController`. Although the safest solution is using a non-optional, and either providing it with a default value, or making it lazy. – Hamish Apr 09 '16 at 11:06
  • Where/when do you set the managed object context in `ViewController`? – vadian Apr 09 '16 at 11:21

1 Answers1

2

No clue why everyone refuses to post an actual answer to the question.

Your variable managedObjectContext is nil. You are probably not injecting it properly before this lazy variable is accessed.

Put a breakpoint on the error line and confirm that your managedObjectContext variable is nil then backtrace to find where you are supposed to be setting it.

Marcus S. Zarra
  • 46,571
  • 9
  • 101
  • 182