Reputation:
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.
Upvotes: 0
Views: 355
Reputation: 26859
You should be able to do this with Key-Value coding. For example:
roomStudents = [aRoom valueForKeyPath:@"@distinctUnionOfSets.isUsedBy.hasStudents"];
See the documentation for more.
Upvotes: 0
Reputation: 828
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.
Upvotes: 1