Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot access an NSManagedObject subclass's properties (gives EXC_BAD_ACCESS)

I am a noob in Core Data with Swift. I have a single NSManagedObject class which looks like this:

import Foundation
import CoreData

class Polls: NSManagedObject {

@NSManaged var title: String
@NSManaged var pollDescription: String

}

In a UITableViewController subclass, I have a method for fetching these objects, like this:

func refreshPolls()
{
    //do the query to populate the array
    let req = NSFetchRequest(entityName: "Polls")
    self.polls = self.managedObjectContext?.executeFetchRequest(req, error: nil) as! [Polls]
    println(polls.count)
}

Note that self.polls is defined as an array of "Polls" objects.

Now, in the cellForRowAtIndexPath: I am simply doing this:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell:UITableViewCell
    if indexPath.row==0
    {
        cell = tableView.dequeueReusableCellWithIdentifier("EditPollCell") as! UITableViewCell
    }
    else
    {

        let poll:Polls = self.polls[indexPath.row-1] as Polls
        //println(poll.title) //fails with EXC_BAD_ACCESS

        cell  = tableView.dequeueReusableCellWithIdentifier("PollCell") as! UITableViewCell
        //cell.textLabel?.text = (poll.valueForKey("title") as! String)


    }

    return cell

That commented println fails with EXC_BAD_ACCESS. No additional error info is given, and adding "dynamic" to the Polls class's attributes makes no difference.

Why can't I access the Polls object's properties? Using the valueForKey method fails with the message "Unexpectedly found a nil value when unwrapping an optional", even though the title property has a value.

like image 254
tutiplain Avatar asked Oct 19 '22 04:10

tutiplain


1 Answers

I assume, that your Polls array is NSManagedObject array. To check this, try to replace:

//println(poll.title) //fails with EXC_BAD_ACCESS

with

println(poll.valueForKey("title"))

If this helps, you can check this answer

CoreData: warning: Unable to load class named

like image 191
Vitalii Gozhenko Avatar answered Oct 30 '22 02:10

Vitalii Gozhenko