fetchRequest is null when calling second time

和自甴很熟 提交于 2021-02-11 15:56:20

问题


The code is

let request: NSFetchRequest<NSFetchRequestResult> = Item.fetchRequest()
print(request)

Item is an entity of Core Data.

The first execution is correct, but when execute it again error occurs Thread 12: EXC_BAD_ACCESS (code=1, address=0x0).

The following is logs:

This is a similar question, but with Object C. It says that defining managedObjectContext in view controller directly instead of transferring it from AppDelegate can fix the bug.

In my code, the managedObjectContext is in SceneDelegate.

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {

    if let windowScene = scene as? UIWindowScene {
        let context = CoreData.stack.context
        let window = UIWindow(windowScene: windowScene)
        window.rootViewController = UIHostingController(rootView: ContentView()
            .environment(\.managedObjectContext, context)
            .environmentObject(UserEnvironment())
    )
        self.window = window
        window.makeKeyAndVisible()
    }
}

and

import CoreData

class CoreData: NSObject {
    
    static let stack = CoreData() 

    public var context: NSManagedObjectContext {
        
        get {
            return self.persistentContainer.viewContext
        }
    }

    private lazy var persistentContainer: NSPersistentCloudKitContainer = {
        
        let container = NSPersistentCloudKitContainer(name: "iCloud.com.xxxx")
        container.loadPersistentStores(completionHandler: { (storeDescription, error) in
            if let nserror = error as NSError? {
                fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
            }
        })
        
        container.viewContext.automaticallyMergesChangesFromParent = true
        container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy
        
        return container
    }()
}

Then how to fix the bug in Swift? Thanks.


回答1:


I fix the bug by change

let request: NSFetchRequest<NSFetchRequestResult> = Item.fetchRequest()

to

let request: NSFetchRequest<NSFetchRequestResult> = NSFetchRequest<NSFetchRequestResult>.init(entityName: "Item")



来源:https://stackoverflow.com/questions/62936616/fetchrequest-is-null-when-calling-second-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!