CoreData - добавление новых отношений к существующей сущности - PullRequest
1 голос
/ 15 февраля 2011

У меня есть следующая основная проблема:

У меня есть две сущности: человек и отдел.

Прежде чем добавить нового человека, я хочу проверить, что отдел еще не существует, и если это так, то связать нового человека с существующим отделом.

Простая вставка с новым отношением отдела:

    Department *department = (Department *)[NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
    department.groupName = @"Office of Personnel Management";

    Person *person1 = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
    person1.name = @"John Smith";
    person1.birthday = [self dateFromString:@"12-1-1901"];
    person1.department = department;

    Person *person2 = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
    person2.name = @"Jane Doe";
    person2.birthday = [self dateFromString:@"4-13-1922"];
    person2.department = department;

    department.manager = person1;
    department.members = [NSSet setWithObjects:person1, person2, nil];

последняя строка делает связь - это нормально.

Но что, если я захочу сделать следующее после выполнения кода выше:

    [self checkForExistingDepartment:@"Office of Personnel Management"];
    if(self.existingDepartment) {

        // here is my Problem number 1:
        // department = ???
        (NSEntityDescription *) department = self.existingDepartment;

    } else {
        Department *department = (Department *)[NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
        department.groupName = @"Office of Personnel Management";

    }   

    Person *person1 = (Person *)[NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.context];
    person1.name = @"John Smith the second one";
    person1.birthday = [self dateFromString:@"12-1-1901"];
    person1.department = department;

    // former line for adding new: department.members = [NSSet setWithObjects:person1, nil];

    // and here is my problem number 2:
    // I think I need something like:  [NSSet addObjects:person1, nil];

В кратком изложении моей проблемой являются дублированные записи в табличном отделе.

Возможно, кто-то знает хороший учебник по CoreData, который подойдет новичку с глубокими знаниями SQL. (Поиск в Google или чтение документации для разработчиков в течение нескольких часов не так полезны, как я думал :))

Для меня, как для начинающего, важно сейчас, на правильном ли пути я или нет, кто-нибудь может это подтвердить?

Спасибо и привет,

Матиас

Ответы [ 2 ]

0 голосов
/ 16 февраля 2011

Извините, функция проверки выглядит так:

- (void) checkForExistingDepartment:(NSString *)searchDepartment {
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Department" initManagedObjectContext:self.context];
    [fetchRequest setEntity:entity];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"country" ascending:YES selector:nil];
    NSArray *descriptors = [NSArray arrayWithObject:sortDescriptor];
    [fetchRequest setSortDescriptor:descriptors];

    NSString *query = searchDepartment;
    if(query && query.length) {
        fetchRequest.predicate = [NSPredicate predicatWithFormat:@"country contains[cd] %@", query];
    }

    NSError *error;
    self.fetchedResultsController = [[NSFetchedResultsController alloc]
                                     initWithFetchRequest:fetchRequest
                                     managedObjectContext:self.context
                                       sectionNameKeyPath:@"section"
                                                cacheName:@"Root"];
    self.fetchedResultsController.delegate = self;
    [self.fetchedResultsController release];
    if(![[self fetchedResultsController] performFetch:&error]) {
        NSLog(@"Error %@", [error localizedDescription]);
    }

    self.existingDepartment = [self.fetchedResultsController objectAtIndexPath:0];
    [fetchRequest release];
    [sortDescriptor release];
}
0 голосов
/ 15 февраля 2011

Вы определяете переменную отдела внутри оператора if/else, а затем используете другую вне его.Попробуйте изменить ваш if так:

[self checkForExistingDepartment:@"Office of Personnel Management"];
if(self.existingDepartment) {
    department = self.existingDepartment;
} else {
    department = (Department *)[NSEntityDescription insertNewObjectForEntityForName:@"Department" inManagedObjectContext:self.context];
    department.groupName = @"Office of Personnel Management";
}

Хотя, не видя код для checkForExistingDepartment, мы не можем вам сильно помочь.,.

...