edounl
edounl

Reputation: 65

Magical record 1 to many relationships objective c

I'm using Magical Record for database with Xcode. I have two entities, one is named 'task' and the other is 'comment', I want to make a relationship so that one task has an array of comments when I query for a task, is it possible, I am new with magical record, hope I made the problem understandable. Thanks.

edit: hey, thanks for your help, i used this code to put the comments in a task:

NSManagedObjectContext *localContext = [NSManagedObjectContext MR_defaultContext];  
     TarefaMR *task = [TarefaMR MR_createInContext:localContext]; task. 

//...

for (NSDictionary *comment in [tarefa objectForKey:@"comments"]) {    NSManagedObjectContext *localContext3 = [NSManagedObjectContext MR_defaultContext];
           ComentarioMR *comment = [ComentarioMR MR_createInContext:localContext3];
       [localContext3 MR_saveToPersistentStoreAndWait];
            [task addComentariosObject:comment]; } 

[localContext MR_saveToPersistentStoreAndWait];

but now i try to access it and i cant seem to get the data from the comments from a task,

code I used :

for (TarefaMR *tarefa in [TarefaMR MR_findAll];)  {   
NSLog(@"tarefa.comentarios %@",tarefa.comentarios);      }

I get a

tarefa.comentarios Relationship 'comentarios' fault on managed object : comentarios = ;

I already tried to loop tarefa.comentarios in a for, but dont seem to get anything, if i query the comments database, the objects are there.

Then for I tried to use:

for (ComentarioMR *comment in tarefa.comentarios) { 
    NSLog(@"comment listHeader %@", comment.listHeader);
    NSLog(@"comment listText %@", comment.listText); }

how can i get the comments of the task?

Upvotes: 0

Views: 1872

Answers (1)

Gianluca Tranchedone
Gianluca Tranchedone

Reputation: 3598

MagicalRecord is only a wrapper around Core Data. You define your entities and their relationships using the Core Data Model Editor in Xcode. You can access this tool by clicking on the file named [your project's name].xcdatamodeld in Xcode. If you don't have such file, you need to create one first.

In this visual editor you can create Entities and add Attributes and Relationships to them. You can then select one of your relationships, go to the inspector in Xcode the section whose icon is represented by a little database and tick the 'To-Many Relationship' box.

If you don't know how Core Data works, I urge you to read the Core Data Programming Guide or at least find some tutorials that explain how it works.

Upvotes: 2

Related Questions