Aj Langley
Aj Langley

Reputation: 127

Why is Xcode not recognizing the attributes of my core data entity

Does anyone have any idea why Xcode isn't recognizing the attributes I set for my entity?

In this block of code, the "authors" attribute works fine:

func createBook() {
        let entityDescription = NSEntityDescription.entityForName("Books", inManagedObjectContext: managedObjectContext!)
        let book = Books(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
        book.name = bookName.text
        book.author = authorField.text
        managedObjectContext?.save(nil)
    }

Here, however, in a function in my TableViewController it says that "book" does not have an attribute "authors":

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell
        let book: AnyObject = newBookViewController.fetchedResultsController.objectAtIndexPath(indexPath)
        cell.textLabel?.text = book.name
        cell.detailTextLabel?.text = book.author
        return cell

Furthermore, when I add more attributes to my Books entity in the entity inspector, even the first function does not recognize them. Also, is this the proper way to save multiple attributes at once?

func bookFetchRequest() -> NSFetchRequest {
        let fetchRequest = NSFetchRequest(entityName: "Books")
        let nameSortDescriptor = NSSortDescriptor(key: "name", ascending: true)
        let authorSortDescriptor = NSSortDescriptor(key: "author", ascending: true)
        fetchRequest.sortDescriptors = [nameSortDescriptor]
        fetchRequest.sortDescriptors = [authorSortDescriptor]
        return fetchRequest
    }

Upvotes: 0

Views: 1273

Answers (1)

Michael
Michael

Reputation: 26

  1. In order for the compiler to know that your book has an author, it has to know it a book.

    let book: AnyObject = newBookViewController.fetchedResultsController.objectAtIndexPath(indexPath)
    

    declares book as AnyObject, which is what objectAtIndexPath returns by default. Since you know it's a book, you can cast it as a book like this:

    let book = newBookViewController.fetchedResultsController.objectAtIndexPath(indexPath) as! Books
    
  2. Unfortunately, adding attributes in the identity inspector does not automatically add them to an existing NSManagedObject. Say you created the Books model without a genre field and you wanted to add that later, you would add it in the identity inspector and then add

    @NSManaged var genre: String
    

    to the Books class.

  3. If you want multiple sort descriptors on a fetch request (e.g. first sort by author, and for books by the same author, sort those by name) then you would do

    fetchRequest.sortDescriptors = [authorSortDescriptor, nameSortDescriptor]
    

Upvotes: 1

Related Questions