在CoreData文档中,我有一个实体SpaceLocation,它由不同的SpaceLocations组成。其中一个是默认/当前编辑文档所必需的。
它在主Document.swift中定义为:
03-20 13:07:32.507 22867-23024/? E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #3
Process: com.example.justcopy, PID: 22867
java.lang.RuntimeException: An error occurred while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:330)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:255)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:776)
Caused by: java.util.ConcurrentModificationException
at java.util.TreeMap$PrivateEntryIterator.nextEntry(TreeMap.java:1232)
at java.util.TreeMap$EntryIterator.next(TreeMap.java:1268)
at java.util.TreeMap$EntryIterator.next(TreeMap.java:1267)
at com.example.adnaneg.copytoclipboard.MainActivity$DeleteData.doInBackground(MainActivity.kt:309)
at com.example.adnaneg.copytoclipboard.MainActivity$DeleteData.doInBackground(MainActivity.kt:305)
at android.os.AsyncTask$2.call(AsyncTask.java:316)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:255)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
at java.lang.Thread.run(Thread.java:776)
并在SpaceLocation类中:
@objc var defaultSpaceLocation: SpaceLocation {
return SpaceLocation.defaultSpaceLocation(in: managedObjectContext!)
}
@objc var currentSpaceLocation: SpaceLocation {
get {
if _currentSpaceLocation == nil {
willChangeValue(for: \Document.currentSpaceLocation)
_currentSpaceLocation = defaultSpaceLocation
didChangeValue(for: \Document.currentSpaceLocation)
}
return _currentSpaceLocation!
}
set {
willChangeValue(for: \Document.currentSpaceLocation)
_currentSpaceLocation = newValue
didChangeValue(for: \Document.currentSpaceLocation)
}
}
我通过以下方式访问currentSpaceLocation:
class func defaultSpaceLocation(in moc: NSManagedObjectContext) -> SpaceLocation {
let spaceLocationsRequest = NSFetchRequest<SpaceLocation>(entityName: "SpaceLocation")
var result:SpaceLocation? = nil
do {
let spaceLocations = try moc.fetch(spaceLocationsRequest)
result = spaceLocations.filter {$0.isBaseLocation}.first!
}
catch {
Swift.print("•••• ERROR ••••", #file, #function, "Couldn't get Default Location")
}
return result!
}
}
但仅当文档位于前台时才有效。当应用进入后台(NSDocumentController.shared.currentDocument as?Document)?.currentSpaceLocation
变为NSDocumentController.shared.currentDocument
时,我无法访问nil
。知道如何解决这个问题吗?