- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
也许你能帮忙,我在其他问题中找不到类似的东西,所以我想我可能会遗漏一些明显的东西。
我有 Swift 中的 CoreData + iCloud 应用程序。
问题场景:
如果我已经在我的设备上登录 iCloud,那么这就可以正常工作。
如果我从 iCloud 注销,那么所有应用程序都可以正常工作,如果我执行问题场景,那么在第 5 步中 NSManagedObject 的 managedObjectContext 为 nil,因此我无法对其进行任何更改,并且由于上下文丢失一旦我需要现有对象的上下文,它当然会崩溃。
我的问题:
我的 CoreDataStack:
class CoreDataStack: CustomStringConvertible
{
static let sharedManager = CoreDataStack()
static let applicationDocumentsDirectoryName = "iCloud.com.myCompany.myAppID"
static let errorDomain = "CoreDataStack"
static let modelName = "DB"
static let storeName = "DB"
static var storeFileName: String
{
return storeName + ".sqlite"
}
var options : [String : AnyObject]?
var inMemory: Bool = false
var description: String
{
var desc = "context: \(self.managedObjectContext)\n" +
"modelName: \(CoreDataStack.modelName)" +
"storeURL: \(self.storeURL)"
desc += "\nPersistent Stores:\n"
for store in persistentStoreCoordinator.persistentStores
{
desc += "* \(store.URL!.absoluteString)"
}
return desc
}
lazy var managedObjectModel: NSManagedObjectModel =
{
let modelURL = NSBundle.mainBundle().URLForResource(modelName, withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator =
{
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
do
{
if self.inMemory
{
try coordinator.addPersistentStoreWithType(
NSInMemoryStoreType,
configuration: nil,
URL: nil,
options: nil)
} else
{
try coordinator.addPersistentStoreWithType(
NSSQLiteStoreType,
configuration: nil,
URL: self.storeURL,
options: self.options)
}
} catch var error as NSError
{
VTLog.error("Persistent Store Error: \(error)")
} catch
{
fatalError("Error creating Persistent Store!")
}
return coordinator
}()
/// The directory the application uses to store the Core Data store file.
lazy var applicationSupportDirectory: NSURL =
{
let fileManager = NSFileManager.defaultManager()
let urls = fileManager.URLsForDirectory(.ApplicationSupportDirectory, inDomains: .UserDomainMask)
let applicationSupportDirectoryURL = urls.last!
let applicationSupportDirectory =
applicationSupportDirectoryURL.URLByAppendingPathComponent(applicationDocumentsDirectoryName)
do
{
let properties = try applicationSupportDirectory.resourceValuesForKeys([NSURLIsDirectoryKey])
if let isDirectory = properties[NSURLIsDirectoryKey] as? Bool where isDirectory == false
{
let description = NSLocalizedString("Could not access the application data folder.",
comment: "Failed to initialize applicationSupportDirectory.")
let reason = NSLocalizedString("Found a file in its place.",
comment: "Failed to initialize applicationSupportDirectory.")
throw NSError(domain: errorDomain, code: 201, userInfo:
[
NSLocalizedDescriptionKey: description,
NSLocalizedFailureReasonErrorKey: reason
])
}
} catch let error as NSError where error.code != NSFileReadNoSuchFileError
{
fatalError("Error occured: \(error).")
} catch
{
let path = applicationSupportDirectory.path!
do
{
try fileManager.createDirectoryAtPath(path, withIntermediateDirectories:true, attributes:nil)
}
catch
{
fatalError("Could not create application documents directory at \(path).")
}
}
return applicationSupportDirectory
}()
/// URL for the main Core Data store file.
lazy var storeURL: NSURL =
{
return self.applicationSupportDirectory.URLByAppendingPathComponent(storeFileName)
}()
lazy var managedObjectContext: NSManagedObjectContext =
{
let context = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
context.persistentStoreCoordinator = self.persistentStoreCoordinator
return context
}()
// ****************************************
// MARK: - iCloud Sync
// ****************************************
var updateContextWithUbiquitousContentUpdates: Bool = false
{
willSet
{
ubiquitousChangesObserver = newValue ? NSNotificationCenter.defaultCenter() : nil
}
}
private var ubiquitousChangesObserver: NSNotificationCenter?
{
didSet
{
oldValue?.removeObserver(
self,
name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
object: persistentStoreCoordinator)
ubiquitousChangesObserver?.addObserver(
self,
selector: #selector(self.persistentStoreDidImportUbiquitousContentChanges(_:)),
name: NSPersistentStoreDidImportUbiquitousContentChangesNotification,
object: persistentStoreCoordinator)
oldValue?.removeObserver(
self,
name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
object: persistentStoreCoordinator)
ubiquitousChangesObserver?.addObserver(
self,
selector: #selector(self.persistentStoreCoordinatorWillChangeStores(_:)),
name: NSPersistentStoreCoordinatorStoresWillChangeNotification,
object: persistentStoreCoordinator)
}
}
@objc func persistentStoreDidImportUbiquitousContentChanges(notification: NSNotification)
{
VTLog.debug("Merging ubiquitous content changes")
VTLog.debug(notification)
self.managedObjectContext.performBlock
{
self.managedObjectContext.mergeChangesFromContextDidSaveNotification(notification)
}
}
@objc func persistentStoreCoordinatorWillChangeStores(notification: NSNotification)
{
VTLog.debug(notification)
if managedObjectContext.hasChanges
{
do
{
try managedObjectContext.save()
} catch let error as NSError
{
print("Error saving: \(error)", terminator: "")
}
}
managedObjectContext.reset()
}
// ***********************************************
// * Data: iCloud Container Actions
// ***********************************************
func deleteiCloudContainer()
{
VTLog.debug("Deleting iCloud Container...")
let currentStore = managedObjectContext.persistentStoreCoordinator!.persistentStores.last!
VTLog.debug("Located data store [\(currentStore)]")
managedObjectContext.reset()
VTLog.debug("managedObjectContext.reset() - OK")
do
{
try managedObjectContext.persistentStoreCoordinator?.removePersistentStore(currentStore)
VTLog.debug("removePersistentStore() - OK")
} catch let error as NSError
{
VTLog.error("Could not remove persistent store [\(currentStore)]: \(error)")
}
do
{
try NSPersistentStoreCoordinator.removeUbiquitousContentAndPersistentStoreAtURL(
currentStore.URL!, options: currentStore.options)
VTLog.debug("removeUbiquitousContentAndPersistentStoreAtURL() - OK")
} catch let error as NSError
{
VTLog.error("Could not remove Ubiquitous Content and Persistent Store at URL [\(currentStore)]: \(error)")
}
}
//*******************************************
// MARK: - Init
//*******************************************
init(inMemory:Bool = false)
{
self.inMemory = inMemory
self.options = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true,
NSPersistentStoreUbiquitousContentNameKey: CoreDataStack.storeName]
}
}
可能有帮助的其他信息:
@ 2016-04-12 11:30:36: AppDelegate: applicationDidEnterBackground:133: (thread): {number = 10, name = main}
@ 2016-04-12 11:30:37: AppDelegate: applicationWillEnterForeground:141: (thread): {number = 11, name = main}
2016-04-12 11:30:37.150 Count Myself[57886:19968276] -PFUbiquitySwitchboardEntryMetadata setUseLocalStorage:: CoreData: Ubiquity: nobody~sim7CC36E42-82CB-5152-91BE-4DD26FE0A420:DB Using local storage: 1 for new NSFileManager current token (null)
@ 2016-04-12 11:30:37: CoreDataStack: persistentStoreCoordinatorWillChangeStores:203: NSConcreteNotification 0x7fd3e8d8fdc0 {name = NSPersistentStoreCoordinatorStoresWillChangeNotification; object = ; userInfo = { NSPersistentStoreUbiquitousTransitionTypeKey = 2; added = ( " (URL: file:///Users/maris/Library/Developer/CoreSimulator/Devices/F9A852DA-595C-4DE2-ADD7-7DECD7D814AD/data/Containers/Data/Application/107B6DB1-C4DC-4626-8933-DACD0575F184/Library/Application%20Support/iCloud.com.myCompany.myAppID/CoreDataUbiquitySupport/nobody~sim7CC36E42-82CB-5152-91BE-4DD26FE0A420/DB/local/store/DB.sqlite)" ); removed = ( " (URL: file:///Users/maris/Library/Developer/CoreSimulator/Devices/F9A852DA-595C-4DE2-ADD7-7DECD7D814AD/data/Containers/Data/Application/107B6DB1-C4DC-4626-8933-DACD0575F184/Library/Application%20Support/iCloud.com.myCompany.myAppID/CoreDataUbiquitySupport/nobody~sim7CC36E42-82CB-5152-91BE-4DD26FE0A420/DB/local/store/DB.sqlite)" ); }} (thread): {number = 12, name = main}
@ 2016-04-12 11:30:37: AppDelegate: applicationDidBecomeActive:152: context: modelName: DBstoreURL: file:///Users/maris/Library/Developer/CoreSimulator/Devices/F9A852DA-595C-4DE2-ADD7-7DECD7D814AD/data/Containers/Data/Application/107B6DB1-C4DC-4626-8933-DACD0575F184/Library/Application%20Support/iCloud.com.myCompany.myAppID/DB.sqlite Persistent Stores: * file:///Users/maris/Library/Developer/CoreSimulator/Devices/F9A852DA-595C-4DE2-ADD7-7DECD7D814AD/data/Containers/Data/Application/436959B5-7850-4156-AB3D-A11BE72FF1AF/Library/Application%20Support/iCloud.com.myCompany.myAppID/CoreDataUbiquitySupport/nobody~sim7CC36E42-82CB-5152-91BE-4DD26FE0A420/DB/local/store/DB.sqlite
stack.updateContextWithUbiquitousContentUpdates = true
但是,如果我不将其设置为 true,我想我不会立即从 iCloud 获取更新。最佳答案
当您退出并重新启动时,应用程序将从内存中删除,因此持久存储和上下文会再次创建并将它们链接在一起。
当您将背景置于背景中,然后提出未发生的情况时,商店和上下文仍然存在。看起来这里发生的是持久存储文件被更改并且上下文与其断开连接(这是一个猜测,我没有测试过)。
因此,看起来在 persistentStoreCoordinatorWillChangeStores
中您应该真正销毁上下文并创建一个新上下文。这也意味着销毁所有来自旧上下文的托管对象并从新上下文获取新版本(假设它们仍然存在)。
关于ios - 从非事件状态恢复应用程序后,NSManagedObject 的 managedObjectContext 变为 nil,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36567966/
因此,我有 CoreData 实体 Book、Bookmark、Highlight。一本书包含关于这本书的信息和一个 Bookmarks 的 NSSet。 我想删除一本书中的书签,然后立即用我的集合重
(如果这个问题有点令人困惑/不精确,我很抱歉。我只是在学习高级 CoreData 用法,我不太了解术语和其他东西)。 我有一个单例 Game,它包含您在游戏过程中需要的某些数据。例如,您可以从那里访问
我有一个基本的 SwiftUI 应用程序,它初始化了 NSPersistentCloudKitContainer在应用程序启动时基于持久堆栈并将 viewContext 注入(inject)环境并将其
我正在将 Core Data 集成到不是使用 Core Data 模板创建的应用程序中。我对此有疑问,可能有一个非常简单的答案。然而,由于大多数关于这个主题的教程都是针对使用模板的,所以我很难过。 我
多个 ManagedObjectContext (MOC) 如何在核心数据中工作(Swift 2、iOS 9)。我浏览了很多在线链接和 Material 以及 StackOverflow 上的答案,但
我正在尝试创建一个新的核心数据对象,并用某个 View 的 subview 的一些信息填充它。 (只是为了用 template_control 对象填充数组) 有什么问题?该对象无法保存,但稍后当我对
我有两个 ManagedObjectContext(MOC):一个临时MOC 和一个持久MOC。如果我在 tempMOC 中初始化一个实体并且用户决定保存,我将保存更改并将更改合并到 persiste
我正在尝试学习核心数据,但在将新对象添加到现有对象后更新 MOC 时遇到问题。我可以创建原始对象(训练日),并且可以将练习对象添加到该训练日,但我不知道如何保存上下文,以便稍后在我的应用程序中可以找到
非常需要建议,目前没有想法。我与核心数据并发相关的问题叠加在一起,调试我使用 -"com.apple.CoreData.ConcurrencyDebug"和我所拥有的: 堆栈: 线程 3 队列:cor
我正在按照教程开发 iOS 应用程序。我正在使用核心数据。应用程序的第一个 View 是 RootViewController。所有核心数据堆栈都在 AppDelegate 文件中。这是 AppDel
我目前正在开发一个发出 HTTP 请求(通过 AsiHTTPRequest)然后解析 JSON 流的应用程序。基本上有一个 tableView/NSFetchedResultsController,它
我有一个应用程序,它使用 CoreData 使用 MPMediaPicker 保存不同的播放列表。保存第一个后,当我尝试添加第二个时,应用程序崩溃了。下面是整个调试队列。 创建第一条记录。 music
如何管理临时保存的 CoreData?一旦我做了这样的事情: var myClass: MyClass = NSEntityDescription.insertNewObjectForEntityFo
在我正在开发的应用程序中,我需要同时访问和写入核心数据。我已经能够收集到这意味着我需要使用多个 managedObjectContexts,但我不明白我应该如何设置这两个 managedObjectC
我是 iOS 开发新手。我正在编写一个允许用户读取/写入核心数据记录的 iOS 应用程序。这些记录将通过 http 同步到服务器。我有一组链式(串行)NSOperations 在执行同步的后台线程中运
我正在尝试将核心数据添加到现有项目中。我有: 1) 添加了核心数据框架2)将访问器和属性添加到 AppDelegate3)创建数据模型文件 现在当我尝试调用NSManagedObjectContext
我想使用单例 UIApplication 来访问 AppDelegate 的 managedObjectContext。但是当我写 [[[UIApplication sharedApplication
在我的 iOS 应用程序中,我有一个核心数据,我注意到有时在特定 View 中,当我从核心数据中检索信息时,并不总是最新的,我解释得很好: 如果我更新核心数据中的一些值,然后进入特定 View 查看此
我在 iPhone 上的核心数据项目遇到问题。当用户开始添加对象,然后在此过程中取消时,就会发生这种情况。 如果用户点击取消并返回到对象列表,则会在那里列出一个虚拟对象,代表他们正在创建的对象。这永远
我有两个实体,我将它们建模为类和核心数据模型实体/这些类如下所示: 类:StateManager #import #import #import "StateManager.h" #import
我是一名优秀的程序员,十分优秀!