错误:将实体添加到 CoreData 时“在实体中找不到键路径索引”

Posted

技术标签:

【中文标题】错误:将实体添加到 CoreData 时“在实体中找不到键路径索引”【英文标题】:Error: "keypath index not found in entity" when adding Entity to CoreData 【发布时间】:2020-05-24 03:21:13 【问题描述】:

我是 ios 开发的新手,我目前正在处理一个项目,该项目涉及一个待办事项列表,该列表在 CoreData 中存储“事件”的实体,以便我能够从这些实体请求数据并在视图中呈现数据.

当我通过点击按钮添加新事件时,出现错误

2020-05-23 20:10:19.478272-0700 simple[47194:7716218] [error] error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x600000af88c0> , keypath index not found in entity <NSSQLEntity Event id=1> with userInfo of (null)
CoreData: error: SQLCore dispatchRequest: exception handling request: <NSSQLFetchRequestContext: 0x600000af88c0> , keypath index not found in entity <NSSQLEntity Event id=1> with userInfo of (null)
2020-05-23 20:10:19.488151-0700 simple[47194:7716218] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'keypath index not found in entity <NSSQLEntity Event id=1>'
*** First throw call stack:
(
    0   CoreFoundation                      0x00007fff23e3cf0e __exceptionPreprocess + 350
    1   libobjc.A.dylib                     0x00007fff50ba89b2 objc_exception_throw + 48
    2   CoreData                            0x00007fff23b0a226 -[NSSQLGenerator newSQLStatementForFetchRequest:ignoreInheritance:countOnly:nestingLevel:nestIsWhereScoped:requestContext:] + 0
    3   CoreData                            0x00007fff23b149f1 -[NSSQLiteAdapter _statementForFetchRequestContext:ignoreInheritance:countOnly:nestingLevel:] + 122
    4   CoreData                            0x00007fff239c76a7 -[NSSQLiteAdapter newSelectStatementWithFetchRequestContext:ignoreInheritance:] + 107
    5   CoreData                            0x00007fff23b67583 -[NSSQLFetchRequestContext _createStatement] + 67
    6   CoreData                            0x00007fff23b6752d -[NSSQLFetchRequestContext fetchStatement] + 142
    7   CoreData                            0x00007fff23b6837e -[NSSQLFetchRequestContext executeRequestCore:] + 33
    8   CoreData                            0x00007fff23bd8291 -[NSSQLStoreRequestContext executeRequestUsingConnection:] + 407
    9   CoreData                            0x00007fff23bab7c8 __52-[NSSQLDefaultConnectionManager handleStoreRequest:]_block_invoke + 56
    10  CoreData                            0x00007fff23b1fb85 __37-[NSSQLiteConnection performAndWait:]_block_invoke + 28
    11  libdispatch.dylib                   0x000000010ea5fe8e _dispatch_client_callout + 8
    12  libdispatch.dylib                   0x000000010ea6eae2 _dispatch_lane_barrier_sync_invoke_and_complete + 132
    13  CoreData                            0x00007fff23b1fa6b -[NSSQLiteConnection performAndWait:] + 145
    14  CoreData                            0x00007fff23bab6dd -[NSSQLDefaultConnectionManager handleStoreRequest:] + 284
    15  CoreData                            0x00007fff23bb1f0f -[NSSQLCoreDispatchManager routeStoreRequest:] + 283
    16  CoreData                            0x00007fff23af0006 -[NSSQLCore dispatchRequest:withRetries:] + 161
    17  CoreData                            0x00007fff23aeb69f -[NSSQLCore processFetchRequest:inContext:] + 88
    18  CoreData                            0x00007fff239c7069 -[NSSQLCore executeRequest:withContext:error:] + 1022
    19  CoreData                            0x00007fff23acb68c __65-[NSPersistentStoreCoordinator executeRequest:withContext:error:]_block_invoke.769 + 3179
    20  CoreData                            0x00007fff23ac3c23 -[NSPersistentStoreCoordinator _routeHeavyweightBlock:] + 233
    21  CoreData                            0x00007fff239c6670 -[NSPersistentStoreCoordinator executeRequest:withContext:error:] + 1486
    22  CoreData                            0x00007fff239c4a54 -[NSManagedObjectContext executeFetchRequest:error:] + 899
    23  CoreData                            0x00007fff23b75277 __43-[NSFetchedResultsController performFetch:]_block_invoke + 327
    24  CoreData                            0x00007fff23ad7ea1 gutsOfBlockToNSPersistentStoreCoordinatorPerform + 177
    25  libdispatch.dylib                   0x000000010ea5fe8e _dispatch_client_callout + 8
    26  libdispatch.dylib                   0x000000010ea6eae2 _dispatch_lane_barrier_sync_invoke_and_complete + 132
    27  CoreData                            0x00007fff23ac361e -[NSPersistentStoreCoordinator performBlockAndWait:] + 173
    28  CoreData                            0x00007fff23a0238d developerSubmittedBlockToNSManagedObjectContextPerform + 154
    29  CoreData                            0x00007fff23a02274 -[NSManagedObjectContext performBlockAndWait:] + 197
    30  CoreData                            0x00007fff23b7550b -[NSFetchedResultsController _recursivePerformBlockAndWait:withContext:] + 144
    31  CoreData                            0x00007fff23b75033 -[NSFetchedResultsController performFetch:] + 254
    32  SwiftUI                             0x00007fff2c8a74b9 $s7SwiftUI12FetchRequestV6updateyyF + 4105
    33  SwiftUI                             0x00007fff2c6a7088 $s7SwiftUI26EmbeddedDynamicPropertyBox33_49D2A32E637CD497C6DE29B8E060A506LLV6update8property7context5phaseSbxz_14AttributeGraph0T7ContextVyAA04VoidT0VGAA01_U6InputsV5PhaseVtF + 24
    34  SwiftUI                             0x00007fff2c8d5bba $s7SwiftUI9BoxVTable33_68550FF604D39F05971FE35A26EE75B0LLC6update3ptr8property7context5phaseSbSv_Sv14AttributeGraph0Q7ContextVyAA04VoidQ0VGAA01_R6InputsV5PhaseVtFZ + 202
    35  SwiftUI                             0x00007fff2c8d4f32 $s7SwiftUI22_DynamicPropertyBufferV6update9container7context5phaseSbSv_14AttributeGraph0J7ContextVyAA04VoidJ0VGAA01_K6InputsV5PhaseVtF + 146
    36  SwiftUI                             0x00007fff2c41d88f $s7SwiftUI19DynamicPropertyBody33_9F92ACD17B554E8AB7D29ABB1E796415LLV6update7contexty14AttributeGraph0P7ContextVyADyxGGz_tF + 479
    37  SwiftUI                             0x00007fff2c41e2f0 $s7SwiftUI19DynamicPropertyBody33_9F92ACD17B554E8AB7D29ABB1E796415LLVyxG14AttributeGraph07UntypedN0AafGP7_update_5graph9attributeySv_So10AGGraphRefaSo11AGAttributeatFZTW + 32
    38  AttributeGraph                      0x00007fff2fc78309 $sTA + 25
    39  AttributeGraph                      0x00007fff2fc60d3d _ZN2AG5Graph11UpdateStack6updateEv + 455
    40  AttributeGraph                      0x00007fff2fc6124b _ZN2AG5Graph16update_attributeEjb + 373
    41  AttributeGraph                      0x00007fff2fc65d53 _ZN2AG8Subgraph6updateEj + 729
    42  SwiftUI                             0x00007fff2c5359e0 $s7SwiftUI9ViewGraphC14runTransaction33_D63C4EB7F2B205694B6515509E76E98BLL2inySo10AGGraphRefa_tF + 224
    43  SwiftUI                             0x00007fff2c535db7 $s7SwiftUI9ViewGraphC13updateOutputs2atyAA4TimeV_tFSb5prefs_Sb9idealSizeAC0F0V7outputstSo10AGGraphRefaXEfU_ + 103
    44  SwiftUI                             0x00007fff2c535a9d $s7SwiftUI9ViewGraphC13updateOutputs2atyAA4TimeV_tF + 125
    45  SwiftUI                             0x00007fff2c81a7db $s7SwiftUI16ViewRendererHostPAAE6render8interval17updateDisplayListySd_SbtFyyXEfU_yyXEfU_ + 811
    46  SwiftUI                             0x00007fff2c819c33 $s7SwiftUI16ViewRendererHostPAAE6render8interval17updateDisplayListySd_SbtFyyXEfU_ + 547
    47  SwiftUI                             0x00007fff2c80f785 $s7SwiftUI16ViewRendererHostPAAE6render8interval17updateDisplayListySd_SbtF + 373
    48  SwiftUI                             0x00007fff2c96f9e2 $s7SwiftUI14_UIHostingViewC14layoutSubviewsyyF + 226
    49  SwiftUI                             0x00007fff2c96fa05 $s7SwiftUI14_UIHostingViewC14layoutSubviewsyyFTo + 21
    50  UIKitCore                           0x00007fff49193678 -[UIView(CALayerDelegate) layoutSublayersOfLayer:] + 2478
    51  QuartzCore                          0x00007fff2b4c6398 -[CALayer layoutSublayers] + 255
    52  QuartzCore                          0x00007fff2b4cc523 _ZN2CA5Layer16layout_if_neededEPNS_11TransactionE + 523
    53  QuartzCore                          0x00007fff2b4d7bba _ZN2CA5Layer28layout_and_display_if_neededEPNS_11TransactionE + 80
    54  QuartzCore                          0x00007fff2b420c04 _ZN2CA7Context18commit_transactionEPNS_11TransactionEd + 324
    55  QuartzCore                          0x00007fff2b4545ef _ZN2CA11Transaction6commitEv + 649
    56  UIKitCore                           0x00007fff48ca3747 __34-[UIApplication _firstCommitBlock]_block_invoke_2 + 81
    57  CoreFoundation                      0x00007fff23da0b5c __CFRUNLOOP_IS_CALLING_OUT_TO_A_BLOCK__ + 12
    58  CoreFoundation                      0x00007fff23da0253 __CFRunLoopDoBlocks + 195
    59  CoreFoundation                      0x00007fff23d9b043 __CFRunLoopRun + 995
    60  CoreFoundation                      0x00007fff23d9a944 CFRunLoopRunSpecific + 404
    61  GraphicsServices                    0x00007fff38ba6c1a GSEventRunModal + 139
    62  UIKitCore                           0x00007fff48c8b9ec UIApplicationMain + 1605
    63  simple                              0x000000010e7d222b main + 75
    64  libdyld.dylib                       0x00007fff51a231fd start + 1
    65  ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

我之前尝试将实体模块分配给当前产品模块,这解决了我之前遇到的问题。该实体具有名称属性:字符串?和 createdAt: Date?

事件实体

import Foundation
import CoreData

public class Event:NSManagedObject,Identifiable 
    @NSManaged public var name: String?
    @NSManaged public var createdAt: Date?


extension Event 
    static func getAllEvents() -> NSFetchRequest<Event> 
        let request: NSFetchRequest<Event> = NSFetchRequest<Event>(entityName: "Event")
        let sortDescriptor = NSSortDescriptor(key: "index", ascending:true)
        request.sortDescriptors = [sortDescriptor]
        return request
    

主视图

import CoreData
import SwiftUI

struct ContentView: View 

    @Environment(\.managedObjectContext) var managedObjectContext
    @FetchRequest(fetchRequest: Event.getAllEvents()) var Events:FetchedResults<Event>
    @State private var newEvent = ""

    var body: some View 
        NavigationView 
            ScrollView 
                Section(header: Text("What's Next?")) 
                    HStack 
                        TextField("New item,", text: self.$newEvent)
                        Button(action: 
                            let toDoItem = Event(context: self.managedObjectContext)
                            toDoItem.name = self.newEvent
                            toDoItem.createdAt = Date()

                            do
                                try self.managedObjectContext.save()
                             catch 
                                print(error)
                            

                            self.newEvent = ""

                        )
                            Image(systemName: "plus.circle.fill")
                                .foregroundColor(.green)
                                .imageScale(.large)
                        
                    
                .padding()
                
            
            .navigationBarTitle("name")
            .navigationBarItems(trailing: EditButton())
        

    

【问题讨论】:

请向我们展示您的数据库定义 【参考方案1】:

您的实体没有“index”属性。您需要使用实体的属性之一更改“index”属性。

let sortDescriptor = NSSortDescriptor(key: "attribute_name", ascending:true)

显然您的实体有两个属性:namecreatedAt

【讨论】:

【参考方案2】:
let sortDescriptor = NSSortDescriptor(key: "index", ascending:true)

这就是问题所在。您正在尝试按 index 属性对获取结果进行排序,但您的实体 Event 没有此属性。你可以改成

let sortDescriptor = NSSortDescriptor(key: "createdAt", ascending:true)

【讨论】:

以上是关于错误:将实体添加到 CoreData 时“在实体中找不到键路径索引”的主要内容,如果未能解决你的问题,请参考以下文章

将 UIImage 作为二进制数据保存到 CoreData 实体时出错

Swift & Core Data - 将实体添加到现有实体

CoreData如何将项目添加到与实体相关的NSSet

SwiftUI 2.0 / CoreData 2021:没有错误但实体未保存

添加新属性时,CoreData 无法完成错误

CoreData:错误 - 实体不是键值编码兼容的 ID