Reputation: 3636
I have a tableview HomeViewController connected to my database (coredata) with a Post entity.
The table view displays correctly. The title of each post is displayed in the cells. But I don't understand something.
When I print post.valueForKey("title"), I have the title. But if I print just println(post) nothing is printed. Why ?
class HomeViewController: UITableViewController, UITableViewDelegate {
private var posts = [Post]()
override func viewWillAppear(animated: Bool) {
let fetchRequest = NSFetchRequest(entityName:"Post")
var sorter: NSSortDescriptor = NSSortDescriptor(key: "date" , ascending: false)
fetchRequest.sortDescriptors = [sorter]
let fetchResultsPosts = CoreDataManager.sharedManager.managedObjectContext!.executeFetchRequest(fetchRequest, error: nil) as? [Post]
println(CoreDataManager.sharedManager.managedObjectContext!) //NOT EMPTY
println(fetchResultsPosts) //NOT EMPTY
if let results = fetchedResults {
posts = results //PRINT optional ([, , , ])
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath:indexPath) as UITableViewCell
let post = posts[indexPath.row] as Post
println(post) // PRINT NOTHING
println(post.valueForKey("title")) //PRINT Optional(Le titre de mon post)
cell.textLabel.text = post.valueForKey("title") as String?
return cell
}
}
In the console :
--->isam.HomeViewController - viewWillAppear<---
Optional(<NSManagedObjectContext: 0x7faa12649150>)
<NSFetchRequest: 0x7faa126919e0> (entity: Post; predicate: ((null)); sortDescriptors: ((
"(date, descending, compare:)"
)); type: NSManagedObjectResultType; )
Optional([, , , ])
--->isam.HomeViewController - tableView(_:cellForRowAtIndexPath:)<---
Optional(Le titre de mon post)
--->isam.HomeViewController - tableView(_:cellForRowAtIndexPath:)<---
I need to understand why, because I have to pass the Post for the next view controller (when user presses a cell).
Upvotes: 0
Views: 766
Reputation: 80265
If you print with println
you need to provide a string.
println(post.description)
I would not worry about it. The post seems to have been retrieved successfully because you can access its attributes. Just pass the object on to your next controller if you need to.
In Core Data, objects are fetched quite efficiently, including a method called "faulting". That means that the attributes of the fetched objects are not fetched right away but only when they are needed. All this is happening behind the scenes, so you do not have to care about it.
Upvotes: 1