ngeran
ngeran

Reputation: 73

Core Data + NSFetchedResultsController in SWIFT

I will try to make it as simple as possible i am fetching from core data using NSFetchedResultsController my cellForRowAtIndexPath looks like this

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
    var cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
    let newEntry : Entry = fetchedResultController.objectAtIndexPath(indexPath) as Entry
    cell.textLabel.text = newEntry.title
    return cell
}

My app crashes

When I replace the line below

let newEntry : Entry = fetchedResultsController.objectAtIndexPath(indexPath) as Entry

With this line the app works records populate tableview no errors no problems

let newEntry : AnyObject! = self.fetchedResultsController.objectAtIndexPath(indexPath)

The question is WHY is not AnyObject is an Entry NSManagedObject

Thank You

Upvotes: 0

Views: 851

Answers (3)

Amateur User
Amateur User

Reputation: 91

Try this out!

if let access:Entry = self.fetchedResultsController.objectAtIndexPath(indexPath) as? Entry {
    cell.textLabel?.text = access.valueForKey("title") as? String
}

And then return to cell

Upvotes: -1

spinach.blue
spinach.blue

Reputation: 11

I faced a similar issue. Now I have successfully rectified it as per the latest iOS version. Hope my code helps.

if let newEntry = fetchedResultsController?.objectAtIndexPath(indexPath) as? Entry{
   cell.textLabel?.text = newEntry.title 
}
return cell

Upvotes: 0

Mashiro
Mashiro

Reputation: 76

There is no problem with NSFetchedResultsController, but Objective-C needs to recognize your NSManagedObject subclass. Just add the @objc(Entry) in your NSManagedObject subclass:

@objc(Entry)
class Entry: NSManagedObject {
    @NSManaged var title: String
}

Upvotes: 3

Related Questions