CoreStore how to fetch or query object from unspecified dynamic object - ios

enter code hereI read this guide which documented pretty good. I need to search through my database and get a record actually execute fetch or query.
Can I search through all records instead of specifying appropriate From clause.
For example
var undefinedObject = CoreStore.fetchAll(
From(GoThroughAllMyDataBaseEntities),
Where("%K == %#", "localId", "some string id")
)
print(undefinedObject.id) // as object will be undefined I need to figure out how to get id property from it.
Side note: all my entities are child objects of parent entity which has id property.
So let's say I have next entities in CoreData:
BaseEntity (which includes id)
Playlist
Song
in the code above I don't care which will be returned to me I just what to see one that matches this condition: Where("%K == %#", "localId", "some string id")
Also my localId property in each objects are very unique strings. They are extracted from NSManagedObjectID.
So there is no way have the same duplicated identifier localy in CoreData
If there is no way to do it, then I will need to loop all my Playlists and Songs records.
managedObjectContext.objectWithID(objectID) may not work thought in some cases as there is no guaranty that CoreData record has not been deleted and app recreated a copy of the same record, so physically a copy of record has another objectID address in CoreData, but still has localID property copied from other record.

Related

Is there a way to access properties of an x-coredata:// object returned from an NSFetchRequest?

TL;DR: Is there a way to programmatically read/recall (NOT write!) an instance of a Core Data entity using the p-numbered "serial number" that's tacked on to the instance's x-coredata:// identifier? Is this a good/bad idea?
I'm using a method similar to the following to retrieve the instances of an Entity called from a Core Data data store:
var managedContext: NSManagedObjectContext!
let fetchRequest : NSFetchRequest<TrackInfo> = TrackInfo.fetchRequest()
fetchResults = try! managedContext.fetch(fetchRequest)
for (i, _) in Global.Vars.numberOfTrackButtons! {
let workingTrackInfo = fetchResults.randomElement()!
print("current track is: \(workingTrackInfo)")
The list of tracks comes back in fetchResults as an array, and I can select one of them at random (fetchResults.randomElement()). From there, I can examine the details of that one item by coercing it to a string and displaying it in the console (the print statement). I don't list the code below, but using workingTrackInfo I am able to see that instance, read its properties into other variables, etc.
In the console, iOS/Xcode lists the selected item as follows:
current track is: <MyProjectName.TrackInfo: 0x60000374c2d0> (entity:
TrackInfo; id: 0xa7dc809ab862d89d
<x-coredata://2B5DDCDB-0F2C-4CDF-A7B9-D4C43785FDE7/TrackInfo/p22>;
data: <fault>)
The line beginning with x-coredata: got my attention. It's formatted like a URL, consisting of what I assume is a UUID for the specific Core Data store associated with the current build of the app (i.e. not a stable address that you could hardcode; you'd need to programmatically look up the Core Data store, similar to the functions we use for programmatically locating the Documents Folder, App Bundle, etc.) The third item is the name of the Entity in my Core Data model -- easy enough.
But that last number is what I'm curious about. From examining the SQLite database associated with this data store, it appears to be a sort of "instance serial number" associated with the Z_PK field in the data model.
I AM NOT interested in trying to circumvent Core Data's normal mechanisms to modify the contents of a managed object. Apple is very clear about that being a bad idea.
What I AM interested in is whether it's possible to address a particular Core Data instance using this "serial number".**
In my application, where I'm randomly selecting one track out of what might be hundreds or even thousands of tracks, I'd be interested in, among other things, the ability to select a single track on the basis of that p-number serial, where I simply ask for an individual instance by generating a random p-number, tack it on to a x-coredata:// statement formatted like the one listed above, and loading the result (on a read-only basis!) into a variable for further use elsewhere in the app.
For testing purposes, I've tried simply hardcoding x-coredata://2B5DDCDB-0F2C-4CDF-A7B9-D4C43785FDE7/TrackInfo/p22 as a URL, but XCode doesn't seem to like it. Is there some other data Type (e.g. an NSManagedObject?) that allows you to set an x-coredata:// "URL" as its contents?
QUESTIONS: Has anyone done anything like this; are there any memory/threading considerations why grabbing instance names in this manner is a bad idea (I'm an iOS/Core Data noob, so I don't know what I don't know; please humor me!); what would the syntax/method for these types of statements be?
Thanks!
You are quite close.
x-coredata://2B5DDCDB-0F2C-4CDF-A7B9-D4C43785FDE7/TrackInfo/p22
is the uriRepresentation() of the NSManagedObjectID of the record.
You get this URL from an NSManagedObject with
let workingTrackInfo = fetchResults.randomElement()!
let objectIDURL = workingTrackInfo.objectID.uriRepresentation()
With this URL you can get the managed Object ID from the NSPersistentStoreCoordinator and the coordinator from the managed object context.
Then call object(with: on the context to get the object.
let persistentStoreCoordinator = managedContext.persistentStoreCoordinator!
if let objectID = persistentStoreCoordinator.managedObjectID(forURIRepresentation: objectIDURL) {
let object = managedContext.object(with: objectID) as! TrackInfo
print(object)
}

Fetching CKRecordZone from a CKRecord

Scenario:
I have a CKRecord which I have fetched from the server. The record exists inside a custom zone for which I do not know the identifier and do not have a CKRecordZone object for.
I need to make a call to CKDatabase.perform(query:inZoneWith:completion:) to get the records in the database which are components of the root shared record (which requires such a call) however without having a CKRecordZoneID (from a CKRecordZone) I am forced to iterate through every CKRecordZone in the shared database and perform the query until a matching record is found.
In summary: I want to take a CKRecord and find the CKRecordZone it exists in. Is this possible? Or is my method flawed and can I perform a query without the CKRecordZoneID?.
To find the CKRecordZoneID of a given record, the recordID property is helpful:
(record).recordID.zoneID yields the CKRecordZoneID that the CKRecord exists in.

Core Data Different Object ID For First Time

I am using Entity's Object ID in order to uniquely identify local notifications and modify them. I observed that first time when I save my entity, it has following object ID:
<x-coredata:///Task/tE1C5A230-A419-42D5-AF78-3327A09D13BD2>
If I don't exit my application, and try to modify notification, object ID doesn't change and I can modify my notification.
Now, if I restart my app and try to access that entity again, it has different object ID:
<x-coredata://D6703834-ECB4-487B-84F8-330A215E16B7/Task/p13>
So I can't modify notification, as object ID for entity is different. Interesting thing is whenever I access that entity, Object ID remains same as the last one.
So my Question here is why Core data shows different object ID for the first time entity is created? When I try to access entity after opening app again for many times, the object ID (different than the first one) remains constant. I am curious to know why is it happening so?
Please note:
I know there are many posts on SO pointing out that using Object ID is not a reliable approach. Still I want to know reason that why two IDs are being shown.
the first OID is a temporary OID - a temporary id denotes objects that have not been saved yet. the 2nd id is a permanent one and is assigned to a MO AFTER it has been saved:
so...
var objectID = object.objectID
if objectID.temporaryID {
object.managedObjectContext.save() //try do catch left out
}
objectID = object.objectID
assert(objectID.temporaryID == false)

CloudKit - How to Save Record If Not Exists

I am trying to make a Record Type that contains unique values, and would act as the target reference objects to another Record Type. For example, Record Type - Movies would contain unique list of movies submitted by users. And FavoriteMovies would contain a Users reference and a Movies reference. Users could select from a list of existing Movies, or add new ones to it.
The problem happens if I create a new Movies record, while another user creates a new record with the same name (after I retrieved the list of movies, but before I attempt to add a new one). The two new records are considered different records with different recordIDs. This means that once I saved the new one, there will be two instances of Movies with the save name.
I'm not able to find a way to perform a Save If Not Exists type operation to the Movies Record Type. I could do a save in the completionBlock of a query, but those two actions would not be an atomic transaction to guarantee uniqueness. As far as I know this is also the case with chaining CKQueryOperation with CKModifyRecordsOperation.
Is there a way to insert a record only if the value does not exists in a single transaction?
If I understood correctly your use case, you can make movieRecord.recordID.recordName the movie's name and use CKModifyRecordsOperation with savePolicy IfServerRecordUnchanged to effectively Save If Not Exists. It would then return an error that you can ignore if you try to save a record that already exists on the server:
let saveRecordsOperation = CKModifyRecordsOperation()
saveRecordsOperation.recordsToSave = [movieRecord]
saveRecordsOperation.savePolicy = .IfServerRecordUnchanged
With the savePolicy IfServerRecordUnchanged this operation will save a new Movie record if it doesn't exist yet on the server (Save If Not Exists) but will return the error below on any subsequent try to overwrite a Movie record that already exists on the server (provided it is not a newer modified version of a record that was fetched from the server):
<CKError 0x14d23980: "Server Record Changed" (14/2017); server message = "record to insert already exists">
You could deal with this conflict in the perRecordCompletionBlock but in your specific use case you can just do nothing about the conflict error so each Movie record will be the first saved record with that CKRecordID.

Predicate for NSFetchRequest Core Data based on content in other entity list

I have the following Core Data Model:
User has attributes username(string) and user_id(integer).
ContactStatus has first_user_id(integer), second_user_id(integer), and status(string which is either "1REQ","2REQ", or "CONF").
I want to get a list of contacts for a given user with a user_id of u_id, the equivalent SQL would be:
SELECT first_user_id,second_user_id FROM ContactStatuses WHERE (first_user_id == u_id OR second_user_id == u_id) AND status == 'CONF'
Or is there a better way to organize my data in Core Data? This is the way its organized in my MySQL database.
Edit:
I have a MySQL database on my server, and in php/sql, if I wanted to return a list of a user's contacts, I would use the above query. As I download this information (in JSON) to my iOS app, I would like to store these users' information in the managed object context. Then, when I want to display a list of contacts to the users, I would want to query the managed object context with a fetch request similar to the above SQL statement. The problem is that I don't know how to filter users with a predicate that comes from a different entity, the contactstatus entity.
CoreData is an object graph representation of your data, in most cases it is backed up by an SQLite database.
I assume that you need to sync your objects with a server side database and so you must define your own user_id property.
However, it might make sense for you to make a relationship between a User entity and a ContactStatus entity (this depend on your implementation and application needs that you have not listed).
In any case, under your current implementation (assuming your query target entity is ContactStatus).
Your predicate should look something like:
[NSPredicate predicateWithFormat:#"(first_user_id = %# OR second_user_id) AND status = %#",#(u_id),#(u_id),#"CONF"];

Resources