ios - 从 NSPredicate 访问实体时的 EXC_BAD_ACCESS

标签 ios swift swift2 nspredicate

将我的应用程序从 iOS7 更新到 iOS9 时,我遇到了这个奇怪的问题。 此代码在 iOS7 和 iOS8 上运行良好,但在使用 iOS9 时,我在尝试获取一个属性的值时收到此错误消息“EXC_BAD_ACCESS”。

这是代码

let fetchRequest = NSFetchRequest(entityName: "Claim")
fetchRequest.predicate = NSPredicate(format: "userType == %d", role)

do
    {
        let retValue = try managedObjectContext.executeFetchRequest(fetchRequest) as! [Claim]

        if (retValue.count > 1)
        {
            for cEntity in retValue
            {
                print("--")
                print("cEntity.claimID: \(cEntity.claimID)")
                print("cEntity.dateCreated: \(cEntity.dateCreated)")  <-- EXC_BAD_ACCESS HERE
             }
         }
    }
    catch {
        print("Error!!!")
    }

在 iOS7 和 iOS8 上打印:

--
cEntity.claimID: 1962872
cEntity.dateCreated: 2015-04-12 22:46:30 +0000
--
cEntity.claimID: 1962839
cEntity.dateCreated: 2015-04-12 22:36:33 +0000

在 iOS9 上打印

--
cEntity.claimID: 1962872

我做错了什么? 如果您需要更多信息,请告诉我。

最佳答案

访问错误是由于属性中的可选值和非可选值造成的。 该属性没有任何值,即 nil,并且您已将其声明为非可选。这就是为什么它尝试访问内存中未分配的值。

要解决这个问题: 1.开放核心数据模型。并将 Claim 属性声明为 选项类型如 dateCreated?

  • 打开“声明”实体。

  • 检查“属性”属性中的“可选”enter image description here

  • 如果值不可用,这将设置 nil 值。

    关于ios - 从 NSPredicate 访问实体时的 EXC_BAD_ACCESS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33013571/

    相关文章:

    swift - 如何将 nil 的可选值设置为空字符串?

    ios - 通过协议(protocol)更新 UILabel 导致崩溃(发现为零)

    ios - iOS 应用程序的最大大小

    ios - 表格 View 中的表格 View swift

    ios - 为什么委托(delegate)在 VIewController 中可以正常工作,但在 UITableViewCell 中不能正常工作?

    ios - 如何在 Swift 3 中设置 UIButton 的图像?

    swift - 在 Swift 2.0 中屏蔽图像

    android - 检查是否通过移动网络登录到 Facebook 应用程序(移动)

    ios - 无法打开文件 “***.app”,因为您没有查看它的权限

    html - 在Swift 2.0中读取HTML文件