views:

157

answers:

2

I'm using Coredata and have a Data Model with the following toMany relationships: Rooms.isUsedBy -> Class many classes use a Room Class.hasStudents -> Students many Students are in a Class

Given the Room I want to get all of the students that use the room. Here is the simplified code:

-(void) studentsinRoom:(Room*)aRoom { NSSet* roomStudents = [[NSSet alloc]init]; for (SchoolClass* aClass in aRoom.isUsedBy) { roomStudents = [roomStudents setByAddingObjectsFromSet:aClass.hasStudents]; } [roomStudents release]; }

roomStudents is computed correctly.
However when exiting the method I get a “EXC_BAD_ACCESS” error.

I'm debuggin this in the iPhone Simulator.

I'm pretty sure that I'm doing/not doing something correctly with the memory management. I do have a break set on "malloc_error_break" and it is not being hit.

+1  A: 

Change it to something like:

- (void) studentsinRoom:(Room*)aRoom
{
    NSSet* roomStudents = nil;
    for (SchoolClass* aClass in aRoom.isUsedBy)
    {
        roomStudents = [roomStudents setByAddingObjectsFromSet:aClass.hasStudents];
    } 
}

The setByAddingObjectsFromSet: method returns an auto-released NSSet object, so you don't want to release it yourself. You're getting the EXC_BAD_ACCESS when the autorelease pool is drained and the object you already released is released a second time.

Just as a side note, the name hasStudents seems confusing, it sounds like it would be a boolean - I think just students would make the code easier to read for that to-many relationship.

Dan Messing
First time user, next time will use code block feature, thanks for the help. hasStudents comes from entity relationship diagrams and is pretty common in that world.
rrgood
A: 

You should be able to do this with Key-Value coding. For example:

roomStudents = [aRoom valueForKeyPath:@"@distinctUnionOfSets.isUsedBy.hasStudents"];

See the documentation for more.

Alex
IMHO this is a better answer than the first though they both work. One minor problem the code should be:[aRoom valueForKeyPath:@"[email protected]"];
rrgood