Master Data NSFetchRequest also retrieves child objects

I am new to iOS dev and Core Data. I have a parent NSManagedObject

@class Units; @interface Properties : NSManagedObject @property (nonatomic, retain) NSString * descr; @property (nonatomic, retain) NSString * address; @property (nonatomic, retain) NSString * city; @property (nonatomic, retain) NSString * state; @property (nonatomic, retain) NSString *zipCode; @property (nonatomic, retain) NSString * imageKey; @property (nonatomic, retain) NSString * numberOfUnit; @property (nonatomic, retain) NSData * thumbnailData; @property (nonatomic, strong) UIImage * thumbnail; @property (nonatomic) double orderingValue; @property (nonatomic, retain) NSSet *units; 

And the baby:

 @class Properties; @interface Units : Properties @property (nonatomic, retain) NSString * unitDescr; @property (nonatomic) int16_t unitNumber; @property (nonatomic, retain) Properties *property; 

When I get the parent properties using this method to display the parent property objects in the table view:

 - (void)loadAllItems { if (!allItems) { NSFetchRequest *request = [[NSFetchRequest alloc] init]; NSEntityDescription *e = [[model entitiesByName] objectForKey:@"Properties"]; [request setEntity:e]; NSSortDescriptor *sd = [NSSortDescriptor sortDescriptorWithKey:@"orderingValue" ascending:YES]; [request setSortDescriptors:[NSArray arrayWithObject:sd]]; NSError *error; NSArray *result = [context executeFetchRequest:request error:&error]; if (!result) { [NSException raise:@"Fetch failed" format:@"Reason: %@", [error localizedDescription]]; } allItems = [[NSMutableArray alloc] initWithArray:result]; } } 

I ran into a problem when the main data context retrieves child objects of the parent entity. I just want to return the parent objects.

For example, if I have a property with 3 units, the tableview property should only display 1 row, but it displays 4 rows (1 parent and 3 children).

How do I return parent objects?

Thanks.

+4
source share
2 answers

If you define Properties as the parent Units object, each Units object is also a Properties object. Therefore, a selection of properties also returns all units.

This is probably not what you wanted. You should simply define the relationship between properties and units without setting the parent object (so both classes are direct subclasses of NSManagedObject ).

Note. I would name the objects Property and Unit, because each instance represents one property or unit.

+4
source

Take a look at the NSFetchRequest setIncludesSubentities method. If your data model reflects your inheritance pattern in your code, then your select query will not retrieve child objects if you configured it correctly.

NSFetchRequest *request = [[NSFetchRequest alloc] init]; request.includesSubentities = NO;

+14
source

All Articles