iOS Core Data - Relationships - iphone

I’m guessing this is a basic question and hopefully someone will be able to point me in the right direction to some sample code, so my question….
I want/have created a core data model that has a parent child relationship, one to many, what I would like to know is what is the correct way to insert child records if the parent already exists. What I’m struggling to understand is how the parent relationship is created when only inserting child records.
Hopefully this makes sense, thanks for any help.

Here You have a series of 3 tutorials: RayWenderlich: Core Data Tutorial
Here a sample app: iPhoneCoreDataRecipes with a more complex data model
Here a Core Data tutorial – One to Many Relationship
Sorry I not respond to your question in his totally. I'm also starting with Core Data, so If You find a good intermediate tuturial, please let me know.
EDIT:
A nice article: Core Data Class Overview

So you'll have Parent and Child. Child will contain a Parent *parentobject while Parent will contain a NSSet *children. Whenever you set the relationship correct in the Datamodel the relationship will be applied automatically when you fill the children set with Child objects.
Please check Articles here

Related

Can an entity have a list/array of items (Core Date, XCode)

I'm very new to Core Data and I have two questions:
I want that all of my Patient entities have property bed which is a value of type bed... Can I create an entity for that too and connect always one patient with one bed?
I wondered if I can do something like every Patient has a property doctors, and that would be a array of doctors "[doctor]". How could I make this.
Thanks, hope you know what I mean, it would be great If someone knows how to do that.
Okay Larme and Joakim Danielson answers my question as comments under my post :)
Their comments:
Yes. The key word you are missing is "relations". You want relationship between your entities. Be it one to one, one to many, many to many. –
Find an online tutorial on learning and using Core Data, many of them handles entity relationships as well –

Why we use ChangeAwareList and ChangeAwareMap

Could you please let me know what is the use of ChangeAwareList and ChangeAwareMap in atg? What problem does it try to solve. I tried reading the documentation but could not find any details regarding the same.
ChangeAwareList and ChangeAwareMap ensure when the parent RepositoryItem has relationships added or removed, when the parent item is updated, that the new relationship are insert/deleted from the database.
If ChangeAwareList and ChangeAwareMap were not used, then when the parent item were being updated/stored to the Repository/database, then you would have to have some logic to loop through each of the existing relationships and compare them to the updated relationships to determine which relationships need to be removed from the database. This is more cumbersome and does not perform as well as the implementation that is "change aware".
This is an example of the Observer design pattern.

create object for hold data in entity-framework

I use entity-framework in my project i want to define and object that the user entry data
And finally insert the all data which user entry in database
But i need an object that hold the data before final insert(like dataset)
please advise me
I think it might be best that you have a further read of the entity framework. There are many examples, articles, threads, etc regarding EF4 and it's predecessors that should help you along your way.
To address what I think you mean by your question, you can take a look at using repository patterns. There are many variations, but here's a link to get you started:
http://blogs.microsoft.co.il/blogs/gilf/archive/2010/01/20/using-repository-pattern-with-entity-framework.aspx
I hope that helps.

Where can I find a good example of a Core Data to-many relationship?

Does anyone have a tutorial or source code that shows a to-many relationship being used, where the user add elements in on the fly? I would just like to have a look because reading about it hasnt been much help.
People are often confused by to-many relationships because one entity represents the relationship as a set while the other represents it as a single object. Take the following entities:
EntityA{
name:string
bees<-->>EntityB.a
}
EntityB{
name:string
a<<-->EntityA.bees
}
In EntityA, the relationship bees is a set because there maybe many EntityB objects in the relationship. So, using Key-Value coding, you would have to access the relationship using a mutableSetForKey: expanding everything out to see the detail would like so:
NSMutableSet *muteSet=[anEntityAObj mutableSetValueForKey:#"bees"];
[muteSet addObject:aNewBObj];
[anEntityAObj setValueForKey:#"bees"];
...or more compactly:
[[anEntityAObj mutableSetValueForKey:#"bees"] addObject:aNewBObj];
If you set from the EntityB side, however, you are only adding a single object so you can just use setValueForKey: directly like so:
[anEntityBObj setValueForKey:anEntityAObj];
That's if you use generic NSManagedObject instances to represent your entities. If you create custom subclasses then you have properties and methods to do the setting for you:
[anEntityAObj addBeesObject:anEntityBObj];
anEntityBObj.a=anEntityAObj;
Remember as well that with managed objects, setting one side of a relationship defined as reciprocal automatically set the other side as well and removing works the same way.
Update
Lets say i've got 2 entities --
Person:with "name" attribute --
Times:with "time" attribute -- i would
want to set multiple times for each
name, but how to I tell it which name
i would like to add the specific times
to?
You don't create relationships with attributes, in this case name but rather with an object, in this case an instances of the Person entity/class. Each individual Person object is completely separate from all other Person objects even if they have the same value in their name attribute.
You must obtain a reference to any particular Parent object. If you have just inserted a new Parent object then you already have a reference to it. If it is already been inserted/persisted, then you create a fetch with a predicate that will return the proper object. Once you have the correct Parent object you then just add the Time objects to the relationship.
So, if your entity looks like this pseudo-code:
Parent{
name:string
times<-->>Time.parent
}
Time{
theTime:date
parent<<-->Parent.times
}
... and you are using generic NSManagedObjects to instatiate you entities, you set the relationship between an existing Parent object and new Time object something like this:
NSManagedObject *existingParent= //... results of a fetch
NSManagedObject *newTime=[NSEntityDescription insertNewObjectForEntityForName:#"Time" inManagedObjectContext:self.moc];
[newTime setValue:[NSDate date] forKey:#"theTime"];
[newTime setValue:existingParent forKey:#"parent"];
Note that if you set the relationship from the Time object's side, you can use setValue:ForKey: because from the Time object's perspective the relationship is just one object to one object.
It is really quite simple once you start thinking in objects instead of databases. Each object you insert in a context is unique even if it shares attributes with other objects of the same entity/class. That is why you can set a relationship between specific objects without necessarily worrying about the values stored in their attributes.
Here is an example of a one-to-many relationship, as long as you have set up the relationships so they have an inverse they are quite easy to manage. at the end, Entity1's chilren attribute will contain entity2 and entity3
Entity1 *entity1=[NSEntityDescription insertNewObjectForEntityForName:#"Entity1" inManagedObjectContext:self.managedObjectContext];
Entity2 *entity2=[NSEntityDescription insertNewObjectForEntityForName:#"Entity2" inManagedObjectContext:self.managedObjectContext];
Entity2 *entity3=[NSEntityDescription insertNewObjectForEntityForName:#"Entity2" inManagedObjectContext:self.managedObjectContext];
[entity2 setParentEntity:entity1];
[entity3 setParentEntity:entity1];
NSError *error;
[[self managedObjectContext]save:&error];
NSSet *set=[entity1 children];
Get Marcus Zarra's book "Core Data" (you can buy a PDF rather than paper for instant gratification...) It too presents examples in Mac OS X but it goes a lot further than just getting started. You will find out useful things like versioning, transition rules, optimization. This book saved one of my projects from being late & slow!
I am currently using this ebook and its very well written:
It explains and shows how to create datamodels and there are also there are code examples..
"Pro Core Data for iOS"
http://apress.com/book/view/1430233559
Hope it helps
Download the iPhoneCoreDataRecipes sample code. It's a full working demo of Core Data and an excellent way to get familiarized with the concepts.
You could try to see in the "Learn Cocoa on the Mac" book sources. In the chapters 7 and 8.
Here for the book
Here for the sources
I hope you'll find what you need
See Apple's Core Data Programming Guide.
I create objects and add them to relationships using mutableSetValueForKey:
mutableSetValueForKey: returns a mutable proxy object. If you mutate its contents, it will emit the appropriate key-value observing (KVO) change notifications for the relationship.
Ray Wenderlich has great Core Data tutorials.
this one deals with to-many relationships
which builds off
this great 3-part intro to core data tutorial

Modelling entity types using Core Data

I'm working on my first app using Core Data and I need to assign a type (with an associated name attribute) to a couple of entities.
Below is my object model so far.
The room and item types will be updated from time to time over the network.
Is this the best way to implement this using Core Data? Thanks :)
Edit: To try to explain better: for example, rooms may be Bedrooms, Kitchens etc. Items can be Aircon, Security Camera etc. The only difference between the different room and item types is the name text. The list of valid name texts will be updated so I don't want to hard code it in the app. Also, the user can create multiple rooms and items of the same type, which is why they are numbered (roomNumber,itemNumber)
improved Core Data Model Image http://img42.imageshack.us/img42/8458/picture6c.png
Nick, try and avoid the temptation of thinking of Core Data as a database. Design your model from the point of view looking at using the objects in your code.
i.e. your relationship properties are collections (or singluars) of the related thing.. you should rename the relationship JobLocation.JobLocationToRoom as just JobLocation.rooms
And yes, using Core Data will be quite straight forward, but it's hard to give you a definitive answer with such a vague question.
Perhaps my question wasn't clear, but I found the answer in the Apple iPhoneCoreDataRecipes demo code
The relationship I wanted to model is similar to Recipe -> RecipeType.
In addition to the other answers, you don't need to model separate ID attributes. Core Data managed objects automatically have managed object IDs that are handled for you entirely behind-the-scenes by the framework.