views:

69

answers:

1

Hello all,

I am new to Core Data programming and am trying to work out the concepts involved. I have an object called a Lease that has a many-to-many relationship with Apartment objects. Given a Lease object, how do I get a count of the related Apartment objects or an NSArray of the related objects?

Thank you!

~~Garth

+3  A: 

There are a couple different ways:

  1. Using the generated Core Data accessor:

    NSSet * apartments = [myLease apartments];
    NSUInteger numberOfApartments = [apartments count];
  2. Using KeyPaths:

    NSSet * apartments = [myLease valueForKey:@"apartments"];
    NSUInteger numberOfApartments = [myLease valueForKeyPath:@"apartments.@count"];
  3. Using KVC (if your class is fully KVC-compliant):

    NSUInteger numberOfApartments = [myLease countOfApartments];
  4. Using a fetch request:

    NSFetchRequest * r = [[NSFetchRequest alloc] init];
    [r setEntity:apartmentEntityDescription];
    [r setPredicate:[NSPredicate predicateWithFormat:@"lease = %@", myLease]];
    NSArray * apartments = [myManagedObjectContext executeFetchRequest:r error:nil];
    NSUInteger numberOfApartments = [myManagedObjectContext countForFetchRequest:r error:nil];
    [r release];

Feel free to mix-and-match those lines.

Dave DeLong