Core Data + NSFetchedResultsController in SWIFT

*爱你&永不变心* 提交于 2019-12-08 11:20:26

问题


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


回答1:


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
}



回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/24783904/core-data-nsfetchedresultscontroller-in-swift

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!