Core Data: Illegal attempt to establish a relationship 'statusmedia' between objects in different contexts - ios

I am using Core Data on my app. After a light weight migration and code upgradation to swift 4.0, I am facing few issues.
Issue 1
Mutating a managed object 0x7fd0881de320 (0x7fd0884589b0) after it has been removed from its context.
Issue 2
Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Illegal attempt to establish a relationship 'statusmedia' between objects in different contexts (source = (entity: Status; id: 0x10f6dc280
Termination issue is very serious.
Note that I have used only one Context (default one and not private)
Let me know if you want more information from me...
Any help would be greatly appreciated.

Many may happen unfortunately to lead to this but top candidates to check would be:
In your model there are delete rules on relations. A "cascade" option should delete the object(s) in relation when deleting this object. If this is not expected such an error could easily be produced.
You are deleting an object but then still use it. It is a logical bug but can be easily confirmed by marking deleted managed objects (put the IDs of deleted objects into some array) and then checking if the failed object is marked (it's ID exists in that array).
You are using multiple contexts but not aware of it. Some tools like fetch result controllers are potential candidates.
There are still other possibilities but I would start with these mentioned to begin with.

Related

Why are Core Data NSManagedObject faults fired upon deletion?

I'm trying to efficiently batch delete a lot of NSManagedObjects (without using an NSBatchDeleteRequest). I have been following the general procedure in this answer (adapted to Swift), by batching an operation which requests objects, deletes, saves and then resets the context. My fetch request sets includesPropertyValues to false.
However, when this runs, at the point where each object is deleted from the context, the fault is fired. Adding logging as follows:
// Fetch one object without property values
let f = NSFetchRequest<NSManagedObject>(entityName: "Entity")
f.includesPropertyValues = false
f.fetchLimit = 1
// Get the result from the fetch. This will be a fault
let firstEntity = try! context.fetch(f).first!
// Delete the object, watch whether the object is a fault before and after
print("pre-delete object is fault: \(firstEntity.isFault)")
context.delete(firstEntity)
print("post-delete object is fault: \(firstEntity.isFault)")
yields the output:
pre-delete object is fault: true
post-delete object is fault: false
This occurs even when there are no overrides of any CoreData methods (willSave(), prepareForDeletion(), validateForUpdate(), etc). I can't figure out what else could be causing these faults to fire.
Update: I've created a simple example in a Swift playground. This has a single entity with a single attribute, and no relationships. The playground deletes the managed object on the main thread, from the viewContext of an NSPersistentContainer, a demonstrates that the object property isFault changes from true to false.
I think an authoritative answer would require a look at the Core Data source code. Since that's not likely to be forthcoming, here are some reasons I can think of that this might be necessary.
For entities that have relationships, it's probably necessary to examine the relationship to handle delete rules and maintain data integrity. For example if the delete rule is "cascade", it's necessary to fire the fault to figure out what related instances should be deleted. If it's "nullify", fire the fault to figure out which related instances need to have their relationship value set to nil.
In addition to the above, entities with relationships need to have validation checks performed on related instances. For example if you delete an object with a relationship that uses the "nullify" delete rule, and the inverse relationship is not optional, you would fail the validation check on the inverse relationship. Checking this likely triggers firing the fault.
Binary attributes can have data automatically stored in external files (the "allows external storage" option). In order to clean up the external file, it's probably necessary to fire the fault, in order to know which file to delete.
I think all of these could probably be optimized away. For example, don't fire faults if the entity has no relationships and has no attributes that use external storage. However, this is looking from the outside without access to source code. There might be other reasons that require firing the fault. That seems likely. Or it could be that nobody has attempted this optimization, for whatever reason. That seems less likely but is possible.
BTW I forked your playground code to get a version that doesn't rely on an external data model file, but instead builds the model in code.
Tom Harrington has explained it best. CoreData's internal implementation apparently requires to fire fault when marking an object to be removed from the persistent store, just like it would if you were accessing a property of the object. As explained in this answer, "An NSManagedObject is always dynamically rendered. Hence, if it is deleted, Core Data faults out the data".
This seems to be the normal behaviour at least for the moment being, not really an issue.

Infrequent CoreData crash "nilOutReservedCurrentEventSnapshot"

There is a crash occurring within my app that only happens quite rarely (maybe once every 30 runs). The error code contains a strange selector name _nilOutReservedCurrentEventSnapshot__ which I haven't been able to find any documentation for at all. Here is the feed from my console:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFType _nilOutReservedCurrentEventSnapshot__]: unrecognized selector sent to instance 0x157b51e0'
*** First throw call stack:
(0x2358810b 0x22d2ee17 0x2358d925 0x2358b559 0x234bbc08 0x24cbf445 0x24ca4d99 0x249bec 0x245c90 0x19b68c 0x24a5c97 0x24b05ab 0x24a8ef9 0x24b1a8d 0x24b18e7 0x232bfb29 0x232bf718)
libc++abi.dylib: terminating with uncaught exception of type NSException
If anyone is able to shed some light on the meaning of this phrase _nilOutReservedCurrentEventSnapshot__`, that would help me immensely. A screenshot of the location of the crash is below:
Unfortunately there isn’t much you can find about _nilOutReservedCurrentEventSnapshot__
online..
It is probably related to the snapshot lifecycle of a managed object.
When Core Data fetches an object from a persistent store, it takes a snapshot of its state. A snapshot is a dictionary of an object’s persistent properties—typically all its attributes and the global IDs of any objects to which it has a to-one relationship. Snapshots participate in optimistic locking. When the framework saves, it compares the values in each edited object’s snapshot with the then-current corresponding values in the persistent store.
The fact that _nilOutReservedCurrentEventSnapshot__ is not documented means that this type of behaviour is not supposed to happen.
What we do know is that it is a function of the NSManagedObject class.
Therefore The error unrecognized selector sent to instance was caused because _nilOutReservedCurrentEventSnapshot__ was called on an object that was not an NSManagedObject, because the NSManagedObject was deallocated and something else now fills its memory. This is fact.
Context isn’t given from the question about the nature of the app and its CoreData setup but it is inferred that it is using a parent-child concurrency pattern. This is important.
[Image retrieved from here]
From all the questions asked on stack overflow that I can find about this error, it appears they all use the parent-child concurrency pattern.
It is entirely possible that the issue is caused by the adoption of this pattern with improper implementation or handling of ManagedObjects.
A Situation where a parent-child context may be used is when syncing cloud data or handling changes made when a user edits something with the option of discarding or undoing the changes made, which can be done on a background thread.
It is also mentioned in the question that this is a rare occurrence and doesn’t happen every time. Meaning that the contexts are probably fine until a certain save or change is made and somehow the contexts become out of sync, and performing another save crashes the app.
From the docs on Synchronising changes between contexts:
If you use more than one managed object context in an application, Core Data does not automatically notify one context of changes made to objects in another. In general, this is because a context is intended to be a scratch pad where you can make changes to objects in isolation, and you can discard the changes without affecting other contexts.
Changes will be sent to the parent context when the child is saved but not if the parent has been changed separately. It is strongly adviced you never change the parent context; only through saving the child context and propagating the changes from there.
Possible reason for crash
There are several things that may cause this but two that stick out are:
1. deallocation of ManagedObject from reference that is disposed of due to dismissing a modal view in an iOS application or sheet in an OSX application.
possible solution: set the retainsRegisteredObjects property of the child context to true before fetching ManagedObjects (and then setting to false once the contexts have been saved to avoid further potential memory leaks). warning!
eg. ctx.retainsRegisteredObjects = true
2. Unhandled changes to a context.
https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/ChangeManagement.html#//apple_ref/doc/uid/TP40001075-CH22-SW1
Consider an application with two managed object contexts and a single persistent store coordinator. If a user deletes an object in the first context (moc1), you may need to inform the second context (moc2) that an object has been deleted. In all cases, moc1 automatically posts an NSManagedObjectContextDidSaveNotification notification via the NSNotificationCenter that your application should register for and use as the trigger for whatever actions it needs to take. This notification contains information not only about deleted objects, but also about changed objects. You need to handle these changes because they may be the result of the delete. Most of these types of changes involve transient relationships or fetched properties.
Possible solutions here are:
Use block methods on your contexts. refer to callback function at bottom of linked file.
Make sure to use objectWithID when passing around ManagedObjects between contexts.
Taking appropriate action on object change using a NSManagedObjectContextDidSaveNotification trigger.
removing all strong references to a ManagedObject. It may be possible that a strong reference was made to a ManagedObject used outside of the scope of the given code and so when the parent deallocated the ManagedObject and the child didn't, on a future save the child performed another save on that ManagedObject and then the parent context tried saving the ManagedObject which was deallocated.
"it is a good pattern to try to fetch objects, modify them, save them and reset the edit [child] context"
Because there is no other information here to deduce what is causing the error, and I can’t reproduce it.. I would suggest trying to find where your ManagedObject is deallocated using Zombie profiling in Instruments.
If a message is then sent to one of these deallocated objects (which are now NSZombie objects), the zombie is flagged, the app crashes, recording stops, and a Zombie Messaged dialog appears. You can then examine the retain and release history of the zombie object to determine exactly where the problem occurred.
https://github.com/iascchen/SwiftCoreDataSimpleDemo/blob/master/SwiftCoreDataSimpleDemo/CoreDataHelper.swift
Hopefully then someone can shed more light on what caused the issue.
+++++++++++++++++++++++++++++++++
Side Note:
parent/child contexts could result in stuttering from the UI - “every fetch request and every save operation will fully block the main thread while data is read or written to/from disk”. Which is because every fetch is pulled through the parent context (on the main thread) to the child.
supporting SO answer
It is recommended that if you are using this approach that you rethink the design to something like two independent managed object contexts connected to the same persistent store coordinator Which might 'avoid' the issue at hand in future from happening.
[Image retrieved from here]
You can see the drastic performance differences in the linked article
_nilOutReservedCurrentEventSnapshot__ is a private method on NSManagedObject internally to flush attributes and values from a Core Data object. You can see it in the private header for NSManagedObject here.
__NSCFType is an private wrapper for Core Foundation types used internally by the Objective-C runtime. You can learn more by looking at the private header here, but there isn't much to see.
Without the full backtrace, it's hard to debug the specific issue. The way I see it, there could be two culprits:
The parentObject of your context is somehow invalid.
You're trying to save a Core Foundation object as a property on an NSManagedObject which isn't expecting it.
A wild guess.. Is there any chance to call this save method from a different thread than the actual thread who created the context? For safer side, always execute Save: operation from perform / PerformBlockAndWait.

Cannot delete objects in other context

I am facing this problem consistently for over 3 months. I have searched a lot and read related docs and visited many forums but couldn't find working solution. I am getting typical NSManagedObject error while deleting objects. An NSManagedObjectContext cannot delete objects in other contexts.
I tried to go around and tried to delete object using its NSManagedObject ID but to no avail.
NSManagedObjectID *findingsSurveyDataItemApiId = [findingsSurveyDataItemApi objectID];
[self.managedObjectContext deleteObject:[self.managedObjectContext objectWithID:findingsSurveyDataItemApiId]];
Can anyone tell why is above solution still not working?
PS: I have two managed object context in the app.
I guess it might be a misleading error message from Core Data. If the object you want to delete has not yet been saved to the persistent store, objectWithID will not return a valid object, according to the docs:
The data in the persistent store represented by objectID is assumed to exist—if it does not, the returned object throws an exception when you access any property (that is, when the fault is fired).
Use existingObjectWithID:error: instead and check if it returns a non-nil object before trying to delete it.

Optimistic locking support in NSIncrementalStore subclass

I am implementing a custom NSIncrementalStore subclass which uses a relational database for persistent storage. One of the things that I still struggle with is the support for optimistic locking.
(feel free to skip this lengthy description right to my question below)
I analyzed how Core Data's SQLite incremental store approaches this problem by examining SQL logs produced by it and came up with following conclusions:
Each entity table in the database has a Z_OPT column which indicates the number of times a particular instance of this entity (row) has been modified, starting from 1 (initial insertion).
Each time a managed object is modified, Z_OPT value in its corresponding database row is incremented.
The store maintains cache (referred to as row cache in Core Data docs) of NSIncrementalStoreNode instances, each having a version property equal to Z_OPT value returned by previous SELECT or UPDATE SQL query on managed object's row.
When a managed object is returned from NSManagedObjectContext (e.g. by executing NSFetchRequest on it), MOC creates snapshot of this object which contains this version number.
When the object is modified or deleted, Core Data makes sure that it has not been modified or deleted outside the context by comparing versions of cached row and object snapshot. All of this happen when -save: is called on the context that the object belongs to. If the versions are different then a merge conflict is detected and handled based on set merging policy.
When MOC is being saved, the -newValuesForObjectWithID:withContext:error: method is called for each modified/deleted object which in turn returns NSIncrementalStoreNode with version number. This version is then compared to snapshot's version and if they are different, the save fails with appropriate merge conflicts (at least with default merge policy).
This simple use case works properly with my store since -newValuesForObjectWithID:withContext:error: checks the row cache first which is enough if the object was concurrently modified in other context using the same store instance. If this is the case, then the cache contains updated row with higher version number which is enough to detect a conflict.
But how can I detect than the underlying database has been modified outside my store, possibly by other application or other store instance using the same database file? I know this is an unfrequent edge case but Core Data handles it properly and I would prefer to do the same.
Core Data's store uses SQL queries like these to update/delete object's row:
UPDATE ZFOO SET Z_OPT=Y, (...) WHERE (...) AND Z_OPT=X
DELETE FROM ZFOO WHERE (...) AND Z_OPT=X
where:
X - version number last known to the store (from cache)
Y - new version number
If such a query fails (no rows affected) the row is updated in store's cache and its version compared against the one previously cached.
My question is: how can a custom NSIncrementalStore inform Core Data that optimistic locking failure has occurred for some updated/deleted/locked objects? It is only the store that is able to tell that when it handles NSSaveChangesRequest passed to it its -executeRequest:withContext:error: method.
If the underlying database does not change under the store, then conflicts are detected since Core Data calls -newValuesForObjectWithID:withContext:error: on each modified/deleted/locked object prior to executing save changes request on the store. I was not able to find any way for NSIncrementalStore to inform Core Data that an optimistic locking failure has occurred after it started to handle the save request. Is there some undocumented way to do that? Core Data seems to throw some exception in that case which is then magically translated into failed save request with NSError listing all the conflicts. I am only able to mimic that partly by returning nil from -executeRequest:withContext:error: and creating the error message by myself. I think there must be a way to use the standard Core Data conflict handling mechanism in this scenario as well.
I realize that this is not an answer to you question, but I will try and give you my point of view on CoreData and correlation to Databases:
(1st level cache)
NSPesistentStoreCoordinator + NSPersistentStore == A single connection to the database
(2nd level cache)
NSManagedObjectContext == cache over the connection holding changes
So, to my understanding your issue is that you have multiple connections to your store, each making changes, but you have no central version control over your records.
Your store will receive a -executeRequest:withContext:error: with NSSaveRequestType
You will then be responsible to verify that the record versions match, if you find a conflict in the connection level (level 1) you report version mismatch between the context (level 2) and the coordinator.
you need to report version missmatch between your connection (level 1) and your store.
To be able to do this your store must report changes on it across all connections to it (ConnectionManager), or it might offer hooks to changes performed on it.
I'm no SQLite expert, but the SQLite API does have something to offer in that area:
update hook
commit hook
changes
total changes
(I have no experience in setting these kind of hooks, but if CoreData use them it will not show in the debug logs)
you can report these errors by setting the error pointer (NSError**) and setting its internal data to match the one that CoreData coordinator is setting (create merge conflict and set the information in them as needed)
Note that optimistic locking failure will only occur during -executeRequest:withContext:error:
(unless you have a rogue connection to the store, one that is not tracked by the manager.
To support this behaviour your manager might need to verify each record as it is committed for a save [huge performance cost] , or use some hooks into the changes recently made to records
)
To handle multiple connections to your store you might need to have a shared cache of NSIncrementalStoreNode, keyed by the store url:
static #{
url1 : actualCacheMapping1,
url2 : actualCacheMapping2,
...
}
each connection save to the store will be verified agains the store url actual cache.
Hope this make some sense for you.
My question is: how can a custom NSIncrementalStore inform Core Data that optimistic locking failure has occurred for some updated/deleted/locked objects? It is only the store that is able to tell that when it handles NSSaveChangesRequest passed to it its -executeRequest:withContext:error: method.
In an NSIncrementalStore, NSIncrementalStoreNodes represent the store snapshots. The version property of the node is the optimistic locking primitive. The persistent store is responsible for detecting optimistic locking failures in at the store level, while the managed object context can detect them higher up. An optimistic locking failure at the store level might happen if the system the store is talking to was changed by something else, and there is a conflict between that system's state and that representation of state in the persistent store. For example, if the store was communicating with a web service and the web service data was changed by another user, etc.
If an optimistic locking failure is detected in your store implementation during a save, your store is responsible for creating NSMergeConflict objects describing it. These will be propagated up by the NSPersistentStoreCoordinator.
[[NSMergeConflict alloc] initWithSource:managedObject newVersion:newVersion oldVersion:oldVersion cachedSnapshot:inMemorySnapshot persistedSnapshot:storedSnapshot];
Snapshot dictionaries should include all modelled attribute property names as keys along with their values. This does not include relationships. For some stores, using the values from the reference objects or NSIncrementalStoreNodes may suffice as long as they only include the modelled attribute property name as keys (and those are easy to get from the entity description).
Once these objects have been created, create an NSError in the NSCocoaErrorDomain with the code NSPersistentStoreSaveConflictsError. The userInfo object should contain the key NSPersistentStoreSaveConflictsErrorKey which should contain an array of the NSMergeConflict objects. Return that from the save request, and the NSPersistentStoreCoordinator will be responsible for finding resolution. Rememeber, you should not generate merge conflicts for conflicts between the state of objects in the NSManagedObjectContext and your store, only for conflicts between whatever in-memory or cached state in your store and where ever the data is kept or persisted (like a web service, or database, etc.)

Strange CoreData error ... value returned from insertNewObjectForEntityForName: appears to be corrupt

I have a very strange error happening in an App that has been working for a long time.
I can no longer create one of my entities in my CoreData model.
When I create one particular entity in my model and try to print it using NSLog( #"%#", obj ), I get this strange message:
2011-11-08 13:03:05.936 iLearnFast[31541:15503] -[__NSCFNumber objectID]: unrecognized selector sent to instance 0xa069e20
When I loop over the attributes / relationships for this object and print them out, one particular one to one relationship returns a strange value from [obj valueForKey:]. The value it returns is the same pointer / object that is mentioned in the above error message.
I thought I might have been corrupting memory somewhere, but I inserted the code to create the entity at the very beginning of my executable as soon as datastructures are initialized, and I get the same problem. I am extremely confident that I have not made any memory errors at this point (and a memory error would be more random ... I can create thousands of objects, and always the same entity has the same problem with the same relationship, and no other entities ever have a problem).
After narrowing down the problem to this one relationship, I found that I could make the error go away by renaming the relationship to anything else. The relationship has been called "file" since my App was created.
I can make my code work again by renaming the property, although it messes up my automatic lightweight migration, but now I have to deal with figuring out how to do a more complicated migration.
If anyone has any ideas as to what might be going wrong, I would really appreciate it.
This is baffling me, and really feels like a bug in Apple's SDK.
I'm currently using XCode 4.2 and tried both the SDKs for both iOS5.0 and iOS4.3 and both had the same behaviour.
Ron
2011-11-08 13:03:05.936 iLearnFast[31541:15503] -[__NSCFNumber
objectID]: unrecognized selector sent to instance 0xa069e20
I guess you have a leak in your code. This line means that you trying to access objectID property which contains in your custom NSManagedObject, but for some reason that object no longer lives. Try to check your code on memory leaks.
I saw this same issue arise in a Swift project using Core Data. The issue only raised it's head when I pushed the app onto a device (it had been working fine in the simulator for some time).
The issue centred around a relationship between two entities. To illustrate see problem image:
After looking around SO for sometime I decided to rename the relationships, captain and player. See fix image:
Only after renaming both 'ends' of the relationship did the error go away.
I had same error message and in my case reason was that I had relation property teacher and created read-only property isTeacher.
This issue caused by Objective-C name conventions: CoreData was confused in getting teacher property. Instead of accessing real relation and giving me real object it taking isTeacher getter with BOOL type, cast it to NSNumber and try to deal with it like CoreData relation and call objectID.
After renaming isTeacher to isTeacherLicence problem gone.

Resources