【问题标题】:Swift dynamic cast exceptionSwift 动态转换异常
【发布时间】:2015-03-22 09:07:34
【问题描述】:

有谁知道为什么我在这个代码块中遇到异常:

override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    var cell = tableView.dequeueReusableCellWithIdentifier("ListCell", forIndexPath: indexPath) as ListTableViewCell
    let item = fetchedResultController.objectAtIndexPath(indexPath) as List
    cell.list_name?.text = item.list_name
    return cell
}

这是我要转换的自定义类:

   import UIKit
   import CoreData

  class List: NSManagedObject {
      @NSManaged var list_name: String
      @NSManaged var items: NSSet
  }

异常发生在这一行:

    let item = fetchedResultController.objectAtIndexPath(indexPath) as List

这是一个例外:

`libswiftCore.dylib`swift_dynamicCastClassUnconditional:
0x10d630860:  pushq  %rbp
0x10d630861:  movq   %rsp, %rbp
0x10d630864:  testq  %rdi, %rdi
0x10d630867:  je     0x10d63089e               ; swift_dynamicCastClassUnconditional + 62
0x10d630869:  movabsq $-0x7fffffffffffffff, %rax
0x10d630873:  testq  %rax, %rdi
0x10d630876:  jne    0x10d63089e               ; swift_dynamicCastClassUnconditional + 62
0x10d630878:  leaq   0xb52e9(%rip), %rax
0x10d63087f:  movq   (%rax), %rax
0x10d630882:  andq   (%rdi), %rax
0x10d630885:  nopw   %cs:(%rax,%rax)
0x10d630890:  cmpq   %rsi, %rax
0x10d630893:  je     0x10d6308ad               ; swift_dynamicCastClassUnconditional + 77
0x10d630895:  movq   0x8(%rax), %rax
0x10d630899:  testq  %rax, %rax
0x10d63089c:  jne    0x10d630890               ; swift_dynamicCastClassUnconditional + 48
0x10d63089e:  leaq   0x36b7d(%rip), %rax       ; "Swift dynamic cast failed"
0x10d6308a5:  movq   %rax, 0xb4c0c(%rip)       ; gCRAnnotations + 8
0x10d6308ac:  int3   
0x10d6308ad:  movq   %rdi, %rax
0x10d6308b0:  popq   %rbp
0x10d6308b1:  retq   
0x10d6308b2:  nopw   %cs:(%rax,%rax)`

【问题讨论】:

  • 有什么异常?
  • 发生在哪里?
  • @Carcigenicate - “哪里”是什么意思?
  • @Dario - 我在帖子中添加了例外。这有帮助吗?
  • @J0NNYZER0 哪一行导致异常?整个程序不会抛出异常;它发生在某条线上。

标签: ios uitableview swift


【解决方案1】:

objectAtIndexPath(_) 返回的对象不是List

如果不保证List,则应始终使用条件强制转换,如下所示:

if let item = fetchedResultController.objectAtIndexPath(indexPath) as? List {
    // item is a List
    cell.list_name?.text = item.list_name
} else {
    // item isn't a List
    // See what it is if you're not expecting this
}

【讨论】:

  • 我的列表是一个自定义类。 objectAtIndexPath(_) 可以是 AnyObject。那不应该让它能够处理我的列表
  • 现在我在控制台中得到了这个异常:2015-03-21 18:42:50.518 MyList[29808:1235523] CoreData:警告:无法为实体加载名为“MyList.List”的类列表'。未找到类,改用默认的 NSManagedObject。
  • 所以我不知道为什么,但大多数教程指示我在实体编辑器的类字段中的类之前应用应用程序名称加一个点,但是当我删除它并放入类时实体编辑器的类字段中的名称它工作正常。
  • @J0NNYZER0 您的核心数据问题很好,但与您在此处提出的问题不同。如果您搜索 Stack Overflow 并没有找到答案,请随时发布新问题。
【解决方案2】:

我认为你必须添加

@objc(List)

在这条线上:

class List: NSManagedObject ...

这是link 中发布的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-02
    • 2013-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多