Error calling on managedobject with EXC_BAD_ACCESS - iphone

I searched a lot for this error and was not able to find a solution.
I have my managedObject:
lazy var managedObjectContext: NSManagedObjectContext = {
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
and I have a Singleton class
lazy var managedObjectContext : NSManagedObjectContext? = {
if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate {
return appDelegate.managedObjectContext
}
return nil
}()
I have a method which is called lot of time whenever I update / delete / load data from database
class func LoadDatabase(tableName: String, predicateString: String, predicateIntValue: Int) -> [AnyObject]? {
do {
let managedObjectContext = Singleton.sharedInstance.managedObjectContext
if managedObjectContext == nil {
return nil
}
let fReq: NSFetchRequest = NSFetchRequest(entityName: tableName)
if predicateString != "" {
fReq.predicate = NSPredicate(format: predicateString, predicateIntValue)
}
var result: [AnyObject]
do {
if managedObjectContext == nil {
return nil
}
result = try managedObjectContext!.executeFetchRequest(fReq)
} catch {
return nil
}
// update exist event
if
result.count != 0 {
return result
}
} catch let error1 as NSError {
print("No values to load for table: \(error1)")
}
return nil
}
I think I have problem on concurrence access. When the app starts it stars asynchronous requests to update the database. But I also call the method LoadDatabase from varius controller. Once the asynchronous call done with updating the datable, it call another method to delete datas which are not more in remote database.
This is what I get. This does not happens always.
I tried to change to MainQueueConcurrency but now I am getting also this error:
2016-03-20 21:27:01.371 Tamil League[1070:245784] CoreData: error: Serious application error. Exception was caught during Core Data change processing. This is usually a bug within an observer of NSManagedObjectContextObjectsDidChangeNotification. -[__NSCFSet addObject:]: attempt to insert nil with userInfo (null)
2016-03-20 21:27:01.371 Tamil League[1070:245784] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFSet addObject:]: attempt to insert nil'
*** First throw call stack:
(0x24a9e2eb 0x2426adff 0x24a9e231 0x249e7fe5 0x261eb683 0x261ea063 0x261e2dfb 0x24a60b21 0x24a5ee17 0x24a5f255 0x249b1bb9 0x249b19ad 0x25c2baf9 0x28c9dfb5 0xa6d5c 0x24664873)
libc++abi.dylib: terminating with uncaught exception of type NSException
Does anyone know how to solve this?

Related

NSPersistentStoreCoordinator not initializing after container.loadPersistentStores

I'm attempting to set up CoreData/CloudKit on a WatchOS application using NSPersistentCloudKitContainer. However, after calling container.loadPersistentStores, the viewContext.persistentStoreCoordinator field appears to still be nil.
Here are some code samples:
Persistence.swift
struct PersistenceController {
static let shared = PersistenceController()
let container: NSPersistentCloudKitContainer
init() {
container = NSPersistentCloudKitContainer(name: "Test")
guard let description = container.persistentStoreDescriptions.first else {
fatalError("Could not retrieve a persistent store description.")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
}
}
MainApp.swift
#main
struct EventLoggerApp: App {
let persistenceController = PersistenceController.shared
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, persistenceController.container.viewContext)
}
}
}
ContentView.swift
struct ContentView: View {
#Environment(\.managedObjectContext) private var viewContext
func createRecord() {
print(viewContext.persistentStoreCoordinator) // this is nil
let sensorReadingDescription = NSEntityDescription.entity(forEntityName: "SensorReading", in: viewContext)! // this crashes
}
}
The error I'm crashing with is:
2020-12-12 11:56:32.205433-0800 EventLoggerWatch WatchKit Extension[400:541990] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+entityForName: nil is not a legal NSPersistentStoreCoordinator for searching for entity name 'Test''
*** First throw call stack:
(0x1f4bb7dc 0x1edc9c04 0x23d68a44 0x174d34 0x174378 0x22fa9d6c 0x231422e0 0x23256ebc 0x22cb86a8 0x23256ed8 0x23256ebc 0x2327a6a4 0x2330f2dc 0x2324cdac 0x2324b6f4 0x2324b75c 0x2324bd20 0x4076df2c 0x40bd9f44 0x40763d70 0x40763e80 0x40763ce8 0x40b986cc 0x40b75abc 0x40becf04 0x40be59b4 0x1f43c4ec 0x1f43c3ec 0x1f43b74c 0x1f435dac 0x1f435574 0x235f94c0 0x40b580f8 0x40b5d5f8 0x350d9b68 0x1eed893c)
libc++abi.dylib: terminating with uncaught exception of type NSException
Please let me know if I can provide any more helpful context, and thanks in advance for the guidance!
Upon further investigation, I'm not sure this question is valid. I think the code listed above was only running for the phone target, and not the watch. There are potentially issues with the watch as well, but I will work on getting the phone working first, as the issues are probably there. Thanks to all who helped out here!

App keeps crashing on save main context into the parent of child context

I'm creating chat application, and created background context for insert, update and delete operations, I have set merge policy type for avoid duplication of msgs into database
but problem is when I am set the parent of child context as main context it crashes the app.
My code for creating backgroung context is
lazy var backgroundContext: NSManagedObjectContext = {
if #available(iOS 10.0, *) {
var managedObjectContext = CoreDataStack.shared.persistentContainer.newBackgroundContext()
managedObjectContext.mergePolicy = NSMergePolicy(merge: NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType)
managedObjectContext.parent = CoreDataStack.shared.getContext()
return managedObjectContext
} else {
var managedObjectContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = CoreDataStack.shared.persistentStoreCoordinator
managedObjectContext.mergePolicy = NSMergePolicyType.mergeByPropertyObjectTrumpMergePolicyType
return managedObjectContext
}
}()
app crashes on line
managedObjectContext.parent = CoreDataStack.shared.getContext()
below is the error i am getting
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Context already has a coordinator; cannot replace
Please help where I am doing wrong

Error: "'NSManagedObjectContext' is not convertible to 'UInt8'"

This is the core data tutorial that I am trying to complete. The error is in the saveContext() function.
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
// ...
func saveContext () {
var error: NSError? = nil
// There second line below this comment is providing for the error referenced in the question title.
let managedObjectContext = self.managedObjectContext
if (managedObjectContext != nil)
{
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if !(_managedObjectContext != nil) {
let coordinator = self.persistentStoreCoordinator
if (coordinator != nil) {
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
// Returns the managed object model for the application.
// If the model doesn't already exist, it is created from the application's model.
var managedObjectModel: NSManagedObjectModel {
if (_managedObjectModel != nil) {
let modelURL = NSBundle.mainBundle().URLForResource("ContactU", withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!)
}
return _managedObjectModel!
}
var _managedObjectModel: NSManagedObjectModel? = nil
// Returns the persistent store coordinator for the application.
// If the coordinator doesn't already exist, it is created and the application's store added to it.
var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if !(_persistentStoreCoordinator != nil) {
let storeURL = self.applicationDocumentsDirectory.URLByAppendingPathComponent("ContactU.sqlite")
var error: NSError? = nil
_persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
if _persistentStoreCoordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: storeURL, options: nil, error: &error) == nil {
/*
Replace this implementation with code to handle the error appropriately.
abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
Typical reasons for an error here include:
* The persistent store is not accessible;
* The schema for the persistent store is incompatible with current managed object model.
Check the error message to determine what the actual problem was.
If the persistent store is not accessible, there is typically something wrong with the file path. Often, a file URL is pointing into the application's resources directory instead of a writeable directory.
If you encounter schema incompatibility errors during development, you can reduce their frequency by:
* Simply deleting the existing store:
NSFileManager.defaultManager().removeItemAtURL(storeURL, error: nil)
* Performing automatic lightweight migration by passing the following dictionary as the options parameter:
[NSMigratePersistentStoresAutomaticallyOption: true, NSInferMappingModelAutomaticallyOption: true]
Lightweight migration will only work for a limited set of schema changes; consult "Core Data Model Versioning and Data Migration Programming Guide" for details.
*/
//println("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
return _persistentStoreCoordinator!
}
var _persistentStoreCoordinator: NSPersistentStoreCoordinator? = nil
// #pragma mark - Application's Documents directory
// Returns the URL to the application's Documents directory.
var applicationDocumentsDirectory: NSURL {
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}
}
In saveContext() your constant managedObjectContext is of type NSManagedObjectContext, yet in the next line you are testing it against nil, which is never possible. Only an optional type (e.g. NSManagedObjectContext?) can be nil. See "Optionals" in The Swift Programming Language: The Basics for more info.
This could be the reason for your error, although it is unclear from the code and error exactly what it is being referred to. Swift's compiler errors aren't all fantastically helpful at this early stage in the development of the language, and so they sometimes need to be taken with a pinch of salt.
I can't give you an answer for sure however you can try this saveContext() way
lazy var managedObjectContext: NSManagedObjectContext? =
{
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil
{
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
func saveContext ()
{
if let moc = self.managedObjectContext
{
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
Besides if you want to pure-swift you shouldn't use "#pragma", Just use // MARK:: - Your tag here

Swift Core Data NSFetchRequest no results

I've encountered a problem when working with Core Data. I have this Core Data Model named 'Test.xcdatamodeld' and it contains only one entity named 'Data'. This Data entity contains one attribute named 'currCount' of type Int32.
What I'm trying to do is to read the value of 'currCount' but when I try to fetch something out of my entity 'Data' there are no results.
This is my fetching code:
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Data")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
var currCount:Int32 = 0
if results.count > 0 {
var res = results[0] as NSManagedObject
currCount = Int32(res.valueForKey("currCount") as Int)
println("Local Count: \(currCount)")
return currCount
}
else {
println("firstTime no Questions")
return 0
}
I always end up in the else-statement. I don't understand what I'm doing wrong. I've been going this way in another project and it works fine.
My AppDelegate.swift is as follows:
import UIKit
import CoreData
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.jqsoftware.MyLog" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Test", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Test.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
EDIT
Even if I save something to currCount before fetching it again, I get 0 results. This is the code I use for saving (which comes before the code above):
var appDel:AppDelegate = (UIApplication.sharedApplication().delegate as AppDelegate)
var context:NSManagedObjectContext = appDel.managedObjectContext!
var request = NSFetchRequest(entityName: "Data")
request.returnsObjectsAsFaults = false
var results: NSArray = context.executeFetchRequest(request, error: nil)!
var currentCount:Int32 = 5
var newCount = NSEntityDescription.insertNewObjectForEntityForName("Data", inManagedObjectContext: context) as NSManagedObject
newHp.setValue(currentCount, forKey: "currCount")
Once you have inserted something on your context, you should save it to make changes permanent (I suppose you are using a SQLite store).
In other words, you need to run a context.save(&error) method.
Update 1
var error: NSError?
if !context.save(&error) {
println("Error saving context: \(error?.localizedDescription)\n\(error?.userInfo)")
}

Swift: Updated and got error: "cannot invoke '!=' with argument list of type.."

Everything was fine in Xcode beta 5 but now in full fledged Xcode I'm getting 2 similar errors in my App Delegate:
"cannot invoke '!=' with argument list of type '(NSManagedObjectContext, NilLiteralConvertible')"
"cannot invoke '!=' with argument list of type '(NSPersistentStoreCoordinator, NilLiteralConvertible')"
I tried replacing the != with !== and I get a different error. I don't see what the problem is with !=.
The code:
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil { //THIS LINE
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
// #pragma mark - Core Data stack
// Returns the managed object context for the application.
// If the context doesn't already exist, it is created and bound to the persistent store coordinator for the application.
var managedObjectContext: NSManagedObjectContext {
if _managedObjectContext !== nil {
let coordinator = self.persistentStoreCoordinator
if coordinator != nil { //THIS LINE
_managedObjectContext = NSManagedObjectContext()
_managedObjectContext!.persistentStoreCoordinator = coordinator
}
}
return _managedObjectContext!
}
var _managedObjectContext: NSManagedObjectContext? = nil
I have a new error: "'NSManagedObjectContext?' does not have a member named 'hasChanges'"
In this code:
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if managedObjectContext != nil {
if managedObjectContext.hasChanges && !managedObjectContext.save(&error) { //This line
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
The reason for this is because NSManagedObjectContext, and probably NSPersistentStoreCoordinator, do not conform to the Equatable protocol. In order to use == and !=, an object needs to conform to this protocol.
=== and !== do not check equality in that sense. These check to see if two objects are in fact the *same object`. Not with similar values. They both point to the same object in memory.
You are able to check this on the two noted types because they are objects. This should work fine for your situation.
About your second issue, your code should look like this:
func saveContext () {
var error: NSError? = nil
let managedObjectContext = self.managedObjectContext
if let moc = managedObjectContext {
if moc.hasChanges && !moc.save(&error) { //This line
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate.
//println("Unresolved error \(error), \(error.userInfo)")
abort()
}
}
}
The difference here is if let moc = managedObjectContext: if managedObjectContext is not nil, the value is stored in the constant moc. Otherwise, whatever is inside does not get executed. You can read more about optionals here.
self.managedObjectContext is here typed as an NSManagedObjectContext, not an NSManagedObjectContext?.
You can't compare a var to nil unless it's of type Optional<>, implements Equatable, or is nil itself.