Skip to main content
 首页 » 操作系统

ios之Swift 动态转换异常

2024年01月01日66虾米哥

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

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 

异常(exception)情况:

`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)` 

请您参考如下方法:

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 
}