问题
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