无法访问NSManagedObject子类的属性(给出EXC_BAD_ACCESS)

tut*_*ain 5 core-data ios swift

我是使用Swift的Core Data中的菜鸟.我有一个NSManagedObject类看起来像这样:

import Foundation
import CoreData

class Polls: NSManagedObject {

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

}
Run Code Online (Sandbox Code Playgroud)

在UITableViewController子类中,我有一个获取这些对象的方法,如下所示:

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)
}
Run Code Online (Sandbox Code Playgroud)

请注意,它self.polls被定义为"轮询"对象的数组.

现在,cellForRowAtIndexPath:我只是这样做:

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
Run Code Online (Sandbox Code Playgroud)

评论println失败了EXC_BAD_ACCESS.没有给出额外的错误信息,并且向Polls类的属性添加"dynamic" 没有任何区别.

为什么我无法访问Polls对象的属性?使用该valueForKey方法失败,并显示消息"在展开可选项时意外发现了nil值",即使该title属性具有值.

Vit*_*nko 3

我假设你的Polls数组是NSManagedObject数组。要检查这一点,请尝试替换:

//println(poll.title) //fails with EXC_BAD_ACCESS
Run Code Online (Sandbox Code Playgroud)

println(poll.valueForKey("title"))
Run Code Online (Sandbox Code Playgroud)

如果这有帮助,您可以检查这个答案

CoreData:警告:无法加载名为的类