CoreData attribute id is needed - ios

I am currently practicing with Swift and Core Data, making an app with a login. When i fetch data from my users entity i receive this:
[<NSManagedObject: 0x7f8f1300c640> (entity: Users; id: 0xd000000000380000 <x-coredata://E67F6A37-4E56-4A55-A01E-940D8BD9EBE9/Users/p14> ; data: {
password = password;
userName = user;})]
Is there a way to obtain de id 0xd000000000380000? I am new using core data and i have only used SQL. I know Core data is not a DB but i think that id is like a primary key, isn't it?
I want to obtain that to use it to find an object of an entity.
Im trying something like this:
data.objectID.uriRepresentation().absoluteString
But it givings me only, it's not what I want to get.
x-coredata://E67F6A37-4E56-4A55-A01E-940D8BD9EBE9/Users/p14

Look at objectID property of your CoreData Entity.
But remember:
If the receiver has not yet been saved, the object ID is a temporary
value that will change when the object is saved.
https://developer.apple.com/documentation/coredata/nsmanagedobject/1506848-objectid?changes=_8

Related

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)

iOS - Core Data set attribute primary key

I am developing an application in Swift and started using Core Data recently.
I must define which attribute to my entity will be my primary key. For example:
I have an entity that has the attributes of the class:
id
name
age
I need the "id" attribute is my primary key.
May be the same in Objective-C, just need to know how to define it.
Each NSManagedObject has its own unique key built in which is available in its objectID property.
This id is internally used to link entities over its relations. There is no need to maintain an own id as a primary key as you are used to do in SQL.
You can always get the id by NSManagedObject.objectID.
Fetching an object by its id can be performed directly by the managed object context using NSMananagedObjectContext.objectWithId(...)
Why do you need id to be your primary key, it's not SQL and there is not primary key (even if behind core data it's SQL you don't use SQL and primary key). Rename your attribute id in userId, or entityId. When you want to get your entity with your id use a NSPredicate:
[NSPredicate predicateWithFormat:#"(entityId == %d)", entityId]

CoreData Unique: Decide update or create

I'm using CoreData in my project and I'm thinking about unique fields and creating objects or updating them if they are already existing.
UseCase:
Get JSON from Server
Map JSON to Object
Save to CoreData
What I want to do is:
Get JSON from Server
Map JSON to Object
Does the object already exists (Unique field is unique identifier for object)
If YES
Get object
Update fields
If NO
Create object
Save to CoreData
Isn't that a lot overhead for the solution? So every time I get an object I have to check the CoreData. Is there something that can do this handeled by CoreData internally?
Have a look a MagicalRecord it has built in maps from JSON to core data and will keep unique items unique.

Best way to have a single Entity using Magicalrecord

I'm looking for the best solution to implement this behavior:
I have an Entity called Customer and this will have only a single entry on Core Data, because the Customer will be only ONE.
What's the best solution to implement this? Is everytime check if the Entity exists before creating?
Many thanks
As mentioned, you can use for single object [NSUserDefaults standardUserDefaults].
But if you prefer use CoreData, write this:
Customer* customer = [Customer MR_findFirst];
if (customer != nil)
{
//do something with it
} else
{
[Customer MR_importFromObject:JSONToImport];
}
BDW:
MR_importFromObject method automatically check if exists entity with specific id (for id key it use attribute of your entity name plus "ID". (in your case "customerID") or key that named "mappedKeyName".
And if entity with this key already exist - Magical Record just update this entity.
So, if you specify this value it in your entity, just write:
[Customer MR_importFromObject:JSONToImport];
If there's only a single instance, the best solution is usually to not put it in Core Data. It gives you very little, and adds complexities like the one you're seeing. Save the necessary information in a property list, or even in user defaults.
Checking the entity exists before creating a new one is a good idea.
You can fetch all entities of your customer entity type and delete them all before adding a new one is another method.
You could also have a simple method that gets the current customer or creates one and then update all it's properties.
It sort of depends on how you get the data and what you want to happen with the related objects.

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