Giving your own ids to Core Data objects - core-data

I have some points on a map with associated informations contained by Core Data, to link the points on the map with the associated info, I would like to have an ID for each point, so in my entity, I would need some ID property, I have read that Core Data has it's own IDs for every managed object but I'm wondering wether or not it would be a good approach for me to directly use them or if I should create my own ID system ?
If you think I should create my OWN ID system, how would I do that ?
Thank you.

CoreData is not an relational database and you should avoid thinking about own ID’s. You may need them only for syncing purposes with external databases. For more precise answer, you should write how your model looks.
[edited after comment]
I don't see that you need any relations. Let's sat you have MapPoint entity with lat, and long properties. If there is only one user note, you just add another property to it like notes. If you have many informations (many records) stored with one MapPoint you need to add Notes entity with properties note and mappoint and make a relation between them. When you insert new Notes object into CoreData you set mappoint property to already existing MapPoint object (fetched after user tap).

Related

Xcode 4.3 Core Data how to make a list?

I am new to iOS development (and objective-C & Xcode 4.3) and I want to create an app with profiles for users. I understand how to use Core Data to make a table with entities and that's all fine, but I don't know how I would go about creating a model so that a user can save a list of items (ie a MutableArray).
For example I need to have a username (for the profile) and than a list of strings that are saved to his account.
Would I need to just create an table with username and string item and than just query for all tuples that contain the username. Is there a simple way to serialize an object and save it the same way it's done in java.
Thank You.
You need to create a one-to-many relationship (which makes a NSSet of "destination" objects, or if you want to keep them in the specified order, click Ordered and it will be a NSOrderedSet).
Once you have the relationship, you can add multiple items to it and access it via the set.

How to create and fetch relational records in core data

Total newbie question now... Suffice to say, I have searched for a completely noddy explanation but have not found anything 'dumb' enough. The problem is...
I have created a core data stack in which I have a entity called 'Client' and an entity called 'Car'. It is a one-to-many relationship.
So far i have successfully created and fetched the client list using code from apple's tutorial. Once I select a client, I then push a new tableViewController which should list the Cars for that chosen client.
First question...
I am used to sql style database programming where if I wanted to add a car to a client, I would simply add a 'ClientID' tag to the 'Car' record thereby providing the relationship to a specific client. How do I do the equivalent in core data? My understanding from my reading is adding attributes to point to other entities isnt necessary - core data maintains this relationship for you without needing additional attributes in the entities.
Second question...
As and when I have created a 'car' entity and successfully linked it to a 'Client'. How to I create a fetch which will retrieve just THAT client's cars. I could alter the code from apple to fetch ALL cars but I don't know how to fetch cars associated with a given client. From my reading, I think I need to use predicates, but apples predicate documentation stands alone and does not give clear guidance on how to use it with core data
I realise how noddy this is, but I cant find an idiots guide anywhere...
Any help/code exmaples much appreciated.
OK, I have answered my own question. For those who have found my question and would like to know the answer, it is extremely simple...
Firstly, to create a 'Car' and associate it with a 'Client'. Firstly create a 'Car' as you normally would and simply add this line of code...
newCar.client = client;
This sets the 'client' relationship on the 'Car' record to the client in question.
Secondly, I had thought that if you had a client and needed to find their cars, you would need a new fetch. But not so! Simply use the following lines of code...
NSSet *cars = client.cars;
[self setCarsArray:[cars allObjects]];
The first line uses "client.cars" o follow the object graph to determine the cars this client has and populates them in an NSSet. The second line then populates a NSArray which is declared in the current viewcontroller which can be used to for display purposes.
Sorted!!

Core Data: Can relationship be used for sectionNameKeyPath?

I am trying to do exactly same thing as post in NSFetchResultsController + sectionNameKeyPath + section order, i.e. basically use 2 tables, let's say Categories <-->> Events. Category table consists of category field only, while Event consists of name, dateTimestamp.
I defined relationship 'category' in Events table and try to use that relationship as sectionNameKeyPath when creating fetchedResultsController:
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:#"category.category" cacheName:#"Root"];
Finally, I pre-populated Category table with some categories upon loading of the app (and verified with .dump that table is populated correctly)
Yet, I simulator fails on:
return [[self.fetchedResultsController sections] count];
I did extensive search and most people either suggest using one of the fields in the table as sectionNameKeyPath (this works!) or transient property (works too!) However, I just want to use relationship as it seems very logical to me in this case where events belong to some categories and there could be categories without events. Am I wrong in my assumption that relationship can be used as sectionNameKeyPath? The original link at the top of the question suggests it works, but guy does not know why or how. Documentation is very weak on what can be used as sectionNameKeyPath, so any help will be highly appreciated.
A relationship gets you a pointer to a managed object. It seems logical, though, that the sectionNameKeyPath parameter should be a key path that leads to a string, since NSFetchedResultsSectionInfo's name property is a string. The fetched results controller will follow that key path for each fetched object and group the objects into sections based on what they return for that key path, and it'll also use those strings as the names of their respective sections. You can't use a managed object for the name -- you have to use some string property of the managed object.
So, your Category entity must have an attribute that distinguishes one category from another, right? Use that as the key path and (as you've seen) everything will work out.
BTW, I think it's useful to try to get out of the database (rows/fields) mindset and try to think in object-oriented terms like entity and attribute. A big selling point of Core Data is that it provides an abstraction layer that hides the storage mechanism. Thinking in terms of tables is like thinking about blocks and sectors when you're reading or writing a file.
Caleb, thank you for your answer. I do believe my understanding was wrong to some degree. What I had was an entity Category and entity Event. Category has a string field 'category', thus 'category.category' path (first 'category' is relationship in the Event entity)
What I did not take in account, though, is that if there are no events, fetchresultscontroller cannot fetch anything (similar to 'left join')
What I wanted is to show categories even if there are no events. Relationship 'category' will not return anything in this case as there is nothing to return/sort/categorize.
What I had to do (wrong or right - not sure yet) is to treat [managed] object created from Category entity as a separate object in case there are no events and place in the table. When there is one event per category, I can switch to the original method of [automatic] showing events sorted by categories.
This is interesting issue of starting point (empty entities with relationships) where I feel core data is more confusing than traditional relationship database. I also believe that's why all books/articles/reports carefully stay away from this topic. In other words, I could not find analog of "left join" in core data. May be I am wrong because I am relatively new to all this. Below is the description of the entities:
Category <-->> Event
Category - parent
Category.category - attribute of type String
Category.event - relationship to Event entity
Event - child
Event.name - attribute of type String
Event.category - relationship to Category entity
Each event belongs to one category. Category may have multiple events.
Categories should be shown even if there are no events for this category.
I was trying to put Events under fetchresultscontroller. May be I should switch to Category first and then calculate cell based on category.event relationship, not the other way around - did not try that yet.

Core Data: Design questions. Object wrappers or not?

I'm designing my first project using Core Data (for iPhone) and Im having some issues that might be related with my design approach.
I'm doing an application that allows the user to create an Order (let's say for a restaurant).
I'm using the graphic designer to model my persistence object (i.e. OrdeMO). I add MO to the ead of each name to indicate its a Managed Object.
I use XCode to create the Managed Object Class automatically.
I have created some "DAO" classes that allows you to search or create a new object in the Managed Context.
Now to my problem.
I want to create an OrderMO object to store the order the user is creating, BUT I don't want it to be part of the context until the user actually places it.
I tried creating the object with [OrderMO alloc] but the object I get is "incomplete" and when I try to set any of its attribute I get an error.
I'm assuming the problem is that I need to create the order IN the context in order to use it. Is that so?
I have considered various options:
Create the object in the context and the user rollback if the user discards the order. The problem is that the user might save other context object during the process (like his prefs) so this doesn't work. Is there a way to create the object "inside a separate transaction" of sorts?
Create a wrapper object that will hold the same data as the MO, and then only create the MO when the user place the order. The downside of this is that I have to maintain a new class.
Create an attribute in the MO, such as "placed", and use to filter my searches in the context. The problem with this one is that I will end up with "trash" objects in the domain (i.e. unplaced orders) and I will have to do some cleanup from time to time...
Do I have any other choice?
Any suggestion is appreciated.
Thanks (for reading this long post!)
Gonso
You should create the OrderMO object in the managed object context and then delete it if the user decides not to place the order.
If the context is saved before the object is deleted, the "trash" object will be deleted from the persistent store on the next save (if the context wasn't saved, the "trash" object will never be saved to the persistent store).
The flag to determine if the order was placed or not does not have to live in the OrderMO object as you suggest in option 3. It could be in the view controller that is tracking the order(s) that are being edited. And, again, you won't have "trash" objects because they will have been deleted.

non-database field on ClearQuest form

Is there a way to use form fields that does not correspond to database field for temporary processings?
I.e. I want to add:
temp fields item1, item2
database field sum
button with record hook that sets sum = item1 + item2
As far as I know it's simply not possible with ClearQuest.
I've tried to do something similar and was told by our IBM consultant that the only way is to create a DB field for all variables.
You can't attach data to form fields really - those are representations of the underlying data, not something scripts interact with directly.
Adding temporary data to the underlying record (entity) itself sounds unlikely as well. Perhaps it's possible to abuse the perl API and dynamically attach data to entity objects but I personally wouldn't try it, you're liable to lose your data at the whim of CQ then ;-)
That does not however mean it's impossible to have temporary data.
The best way seems to me to be using the session object, which is explicitly intended for that purpose.
From the helpfile:
IBM Rational ClearQuest supports the
use of sessionwide variables for
storing information. After you create
sessionwide variables, you can access
them through the current Session
object using functions or subroutines,
including hooks, that have access to
the Session object. When the current
session ends, all of the variables
associated with that Session object
are deleted. The session ends when the
user logs out or the final reference
to the Session object ceases to exist.
There's some helpful documentation on this subject in file:///C:/Program%20Files/Rational/ClearQuest/doc/help/cq_api/c_session_vars.htm (Presuming a default installation on a windows machine, of course.)
Translating the code example in there into what you seem to be wanting, first you store the data you have calculated inside the session object:
$session->SetNameValue("item1", $value1);
$session->SetNameValue("item2", $value2);
Then in your calculation hook you retrieve the stored values and set the value of that totals field like this:
my $item1 = GetNameValue("item1");
my $item2 = GetNameValue("item2");
my $sum = $item1 + $item2;
$entity->SetFieldValue("some_totals_record", $sum);
Adjust to taste of course ;-)
ClearQuest schema designers often include 'temporary' fields in their record types. They do this so they perform operations on hooks to generate another value.
For example, for the Notes fields, there is a 'temporary' Notes_entry field that the user types the most recent note into, and when the record is saved, the value is added to the Notes_Log field. The next time the record is edited the Notes_entry field is cleared so the user can type a new Notes_entry.

Resources