在核心数据中获取具有关系的实体

时间:2011-07-08 20:01:12

标签: ios core-data uitableview entity-relationship

我的核心数据数据库中有2个实体PersonPhoto PersonTo-ManyPhoto个关系,而Photo有与Person (Person<-->>Photo)的反向关系。我以下列方式从.plist中为我的应用程序加载了一些初始数据:

-(void)populateDataStorage{

    NSString *path = [[NSBundle mainBundle] pathForResource:@"FakeData" ofType:@"plist"];

    if(path){
        NSArray *plistData = [[NSArray alloc] initWithContentsOfFile:path];
        NSEnumerator *enumerator = [plistData objectEnumerator];

        NSArray *personResults;

        Photo *photo;
        Person *person;

        id currItem = [enumerator nextObject];

        while (currItem != nil) {
            photo = (Photo *)[NSEntityDescription insertNewObjectForEntityForName:@"Photo" inManagedObjectContext:[flickrFetcher managedObjectContext]];

            photo.name = [currItem objectForKey:@"name"];
            photo.path = [currItem objectForKey:@"path"];

            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"name = %@", [currItem objectForKey:@"user"]];

            personResults = [flickrFetcher fetchManagedObjectsForEntity:@"Person" withPredicate:predicate];

            if ([personResults count] > 0) {
                person = [personResults objectAtIndex:0];
            } 
            else {
                person = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:[flickrFetcher managedObjectContext]];
                person.name = [currItem objectForKey:@"user"];
            }

            photo.person = person;
            [person addPhotosObject:photo];

            NSLog(@"Photo %@ added for user %@", photo.name, person.name);

            currItem = [enumerator nextObject];
        }

        [plistData release];

    }

}

一切都正常加载。然后我使用NSFetchedResultsController获取Person并加载UITableView,这一切都有效。当用户点击属于用户的单元格时,我必须使用所选人员的照片加载另一个UITableView,所以我在我的UITableViewController中为照片的表格视图执行以下操作:

 - (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person = %@", person];
        self.fetchedResultsController = [[FlickrFetcher sharedInstance] fetchedResultsControllerForEntity:@"Photo" withPredicate:predicate];
    }
    return self;
}

在我的viewDidLoad

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSError *error = nil;
    [fetchedResultsController performFetch:&error];

    for(Photo *photo in person.photos){
        NSLog(@"Photo %@ belongs to %@", photo.name, person.name);
    }

    NSLog(@"Photo count %d", [[fetchedResultsController fetchedObjects] count]);
}

伯爵给了我0,我从来没有得到人物的照片,但我知道他们已经妥善保存了,因为他们都打印出传递给Person。知道我可能做错了吗?

修改

NSFetchedResultsController课程中获取FlickrFetcher的实用方法:

- (NSFetchedResultsController *)fetchedResultsControllerForEntity:(NSString*)entityName withPredicate:(NSPredicate*)predicate {
    NSFetchedResultsController *fetchedResultsController;

    /*
     Set up the fetched results controller.
     */
    // Create the fetch request for the entity.
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    // Edit the entity name as appropriate.
    NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:[self managedObjectContext]];
    [fetchRequest setEntity:entity];

    // Set the batch size to a suitable number.
    [fetchRequest setFetchBatchSize:20];

    // Edit the sort key as appropriate.
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];

    [fetchRequest setSortDescriptors:sortDescriptors];

    // Add a predicate if we're filtering by user name
    if (predicate) {
        [fetchRequest setPredicate:predicate];
    }

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

    [fetchRequest release];
    [sortDescriptor release];
    [sortDescriptors release];

    return [fetchedResultsController autorelease];
}

我自己NSFetchedResultsController创建的UITableViewController

NSFetchRequest *request = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Photo" inManagedObjectContext:[flickFetcher managedObjectContext]];

    [request setEntity:entity];

    NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:descriptor, nil];

    [request setSortDescriptors:sortDescriptors];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"person = %@", person];

    [request setPredicate:predicate];

    fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:[flickFetcher managedObjectContext] sectionNameKeyPath:nil cacheName:@"Root"];

    [request release];
    [descriptor release];
    [sortDescriptors release];

    NSError *error = nil;
    [fetchedResultsController autorelease];
    [fetchedResultsController performFetch:&error];

我没有看到差异。

1 个答案:

答案 0 :(得分:1)

不要随便看到任何东西。我插入所有测试数据后,我想在上下文中插入一个保存。 (下次不要插入它。)

一条评论:

photo.person = person;
[person addPhotosObject:photo];

这是多余的。如果设置另一个,则在核心数据中使用反向关系建模的关系将正确设置反向关系。因此,只需要其中一条线。