How does one retrieve the NSManagedObjectID when saving an object to Core-Data?
I have a series of objects to save to Core-Data and I need to have each ones objectID as I am saving on another thread.
I would then like to pass this array to the main thread and fetch the objects for the array of IDs.
You can use key value coding which is very convenient:
NSArray *objects; // the objects you are saving
NSArray *objectIDs = [objects valueForKeyPath:#"objectID"];
However, this does not make too much sense. Why don't you just pass the array of objects right away? You could also retrieve them from the store with a suitable predicate.
Related
Im currently having a problem with my CoreData implementation. I try to query the number of objects with certain properties. I therefore execute the following code
NSUInteger itemsCount = [managedObjectContext countForFetchRequest:fetchRequest error:NULL];
NSLog(#"%i",(int)itemsCount);
So far so good. Everything works if i work with a fresh MOC where no data has ever been saved. The problem occures when i do the following:
I save the whole MOC
Delete one of those objects matching the fetch criteria from the MOC (without saving!)
Requery the Number of objects matching the criteria
The number of objects does not change although i deleted one of the objects.
I also tried the following query ...
fetchRequest.resultType = NSCountResultType;
NSArray* array = [managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
NSLog(#"%i",[[array firstObject] intValue]);
... with the same result.
Then I tried querying the objects directly ...
fetchRequest.resultType = NSManagedObjectResultType;
array = [managedObjectContext executeFetchRequest:fetchRequest error:&fetchError];
NSLog(#"%i",(int)[array count]);
... tada: Here it works. The array does not contain the deleted object.
When I set fetchRequest.includesPendingChanges = NO, i of course get all objects because i did not save yet. The property has no effect ob the first two queries though because they show too many objects in the first place.
So my question is, what am i doing wrong and why can i not obtain the right amount of objects once i saved them to the persistence store. Do i have to reset the MOC after saving?
--------------------------------------------------------------------------------
Update
I searched further for similar problems and found some interesting posts. Fetching objects from the MOC means also querying the persistence store. Since I did not save my changes immediately, I do or don't fetch deleted and newly inserted objects respectively. But strangely this only applies for queries involving dictionary result types or count fetches. When querying the objects itself i retrieve the correct number of objects including newly inserted and without the deleted ones.
Now I am wondering on how to deal with my problem. I have a table view which smoothly works with a NSFetchedResultsController (NSFRC). I do not have to save any changes since the controller handles all the updates and notifies me. But as soon as i insert or delete data and the NSFRC notifies me, i want to do further calculations to update my other views. Those calculations include average and number of objects with certain attribute etc.
Right now I update those view as soon as an insert or delete delegate method is being called. But those queries wont return the correct values.
Calling the following before querying has no effect on those queries.
[moc processPendingChanges]
fetch.includePendingChanges = YES
Apparently my approach is lacking something. How do i fetch my needed values correctly ? Since my NSFRC obviously keeps track of deleted and inserted values im curious if it would help to create a second NSFRC just to fetch the averages and so on? Is it even capable of that?
Thanks!
NSIncrementalStore has a required method "obtainPermanentIDsForObjects".
To get the ID's I have to create new row's in the database. Then to save the data in
executeRequest:withContext:error:, I have to hit the DB again.
Is there a reason why I shouldn't get new rowID's and save the data at the same time in obtainPermanentIDsForObjects?
The answer is probably not, if your entities have relationships.
To save a relationship, you need to uniquely identify the corresponding objects. Identifying an object requires your internal identifier which can be obtain via the permanent objectID (NSManagedObjectID).
But (some of) your objects won't have a permanent and internal ID yet because they haven't been handled yet in "obtainPermanentIDsForObjects"
In other words first you need to assign permanentID's (and thus also internalID's) before you can save references to them.
Whenever I add a new object to core data, and get the results using a NSFetchRequest, the array it returns is not in the order of which I added the objects. Is this supposed to be like this? How would I fix this?
Yes, data stored in CoreData is not ordered in any way. If you want it ordered, you need to add an attribute that you want to sort on and then add a sort descriptor to the fetch request.
Every time I Save a new Object it appears on the top of my UITableView. What If want it to apper at a different index path or different section?
For Example is it Possible to insert the new Object at:
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[[self objectsFetched] count]-1 inSection:0];
or
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[[self objectsFetched] count]-1 inSection:1];
I Can accomplish the above scenario with NSMutableArrays, but how do I achieve the same with Core Data?
With Core Data you have a big bag of contents, how you display that in a table view is entirely up to you. The process of achieving this is by sorting the big bag, generally as you extract the contents.
Look at NSFetchRequest and you will see it takes an array of sortDescriptors. You can make these sort descriptors look at any key in your managed objects. If you want, you can add an explicit order key and set the value, or a date stamp.
How you sort is up to you, but you do need to sort to specify the order you want.
is there a simple and efficient/fast way to query a managedobjectcontext to get an array of all the managedobjects in the context that have not yet been added to the persistent store?
i ask this because i would like to be able to save nsmanagedobjects that have been added to the MOC only if they conform to certain criteria. basically i want to be able to do this so that if some unexpected event happened before my managed object attributes were properly populated, i can catch this fact and purge the object(s) before saving the context. given the complexity of the navigation possible in the app, i'd like to have a look at the data to be sure they are good before i save.
i suppose i could also do this with some kind of validation rule and a flag field that doesn't get set until i am sure the user has added all the data to the record, but i don't yet know how to implement this...
any help much appreciated.
The insertedObjects method of NSManagedObjectContext
returns the set of objects that have been inserted into the context but not yet saved in a persistent store.