开发者

Accesing sub entity reletionship/property in NSFetchedResultsController

I'm trying to acces a property from a managedobject relationship in one of my entity but i keep getting a "nil" object from it. Here's a summary of the entities and there relation.

Entity: House Relationships: adress (1 to 1)

Entity: Adresse Properties: street (NSString) Relationships: house (1 to 1)

So basically a "House" can only have one "Adresse". I want to be able t开发者_JAVA技巧o sort by the street property from the adress relationship when i fetch a House. Here's the code that i'm using but can't seem to make it work out. What am i missing?

- (NSFetchedResultsController *)fetchedResultsController {
    // Set up the fetched results controller if needed.
    if (fetchedResultsController == nil) {

        MyAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate]; 
        NSManagedObjectContext *managedObjectContext = [appDelegate managedObjectContext]; 

        // Create the fetch request for the entity.
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        // Edit the entity name as appropriate.
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"House" inManagedObjectContext:managedObjectContext];
        [fetchRequest setEntity:entity];

        // Edit the sort key as appropriate.
        NSString *sectionKey = @"adresse.rue";
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:sectionKey ascending:YES];
        NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

        [fetchRequest setSortDescriptors:sortDescriptors];
        [fetchRequest setFetchBatchSize:20];

        // Edit the section name key path and cache name if appropriate.
        // nil for section name key path means "no sections".
        NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:managedObjectContext sectionNameKeyPath:sectionKey cacheName:@"House"];
        aFetchedResultsController.delegate = self;
        self.fetchedResultsController = aFetchedResultsController;

        [aFetchedResultsController release];
        [fetchRequest release];
        [sortDescriptor release];
        [sortDescriptors release];
    }

    return fetchedResultsController;
}    


Your code looks OK. Your fetch request is valid. If it's not throwing any exceptions, then your key path is specified properly.

I'm not quite sure what you mean by "getting a nil object from it". If you mean your fetched results controller doesn't contain any objects, make sure that you're calling performFetch: before you try accessing any objects. The controller will be empty until you do this.

Does this code work when you leave out the sort descriptors and key path?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜