如何查询财产是否存在关联关系?

发布于 2024-11-11 16:42:07 字数 3319 浏览 3 评论 0原文

我有一个实体Session。在我看来,实体Exercise可以添加到Session中。

在保存之前,我想检查是否与Session有任何关系,如果没有,我将在保存之前删除该对象。

谁能告诉我该怎么做?

编辑:

- (void)createSession
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *dateComponentsForToday = [calendar components:unitFlags fromDate:self.picker.date];
    [dateComponentsForToday setHour:0];
    [dateComponentsForToday setMinute:0];
    [dateComponentsForToday setSecond:0];
    NSDate *targetDateBegins = [calendar dateFromComponents:dateComponentsForToday]; 
    NSDate *targetDateEnds = [targetDateBegins dateByAddingTimeInterval:(60 * 60 * 24 - 1)];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat: @"(timeStamp >= %@ && timeStamp <= %@)", targetDateBegins, targetDateEnds]];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];
    NSLog(@"timeStamp >= %@ && timeStamp <= %@", targetDateBegins, targetDateEnds);

    NSError *error = nil;
    NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    NSLog(@"Fetch error: %@", error);

    if ([results count])
    {
        session = (Session *)[results objectAtIndex:0];
    }
    else
    {
        session = (Session *)[NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:managedObjectContext];
        session.timeStamp = self.picker.date;
    }

    NSSet *filteredExercisesFromSession = [session.exercises filteredSetUsingPredicate:[NSPredicate predicateWithFormat: @"name == %@",selectedExerciseName]];
    if ([filteredExercisesFromSession count] > 0)
    {
        self.exercise = [filteredExercisesFromSession anyObject];
    }

    [fetchRequest release];
    self.fetchedResultsController = nil;
    [setsTableView reloadData];
}

-(IBAction)createSet
{    
    NSSet *filteredExercisesFromSession = [session.exercises filteredSetUsingPredicate:[NSPredicate predicateWithFormat: @"name == %@",selectedExerciseName]];

    if ([filteredExercisesFromSession count] > 0)
    {
        self.exercise = [filteredExercisesFromSession anyObject];
    }
    else
    {
        NSLog(@"exercise does not already exist");
        self.exercise = (Exercise *)[NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:managedObjectContext];
        self.exercise.name = selectedExerciseName;
        self.exercise.muscleGroup = muscleName;
        [session addExercisesObject:exercise];
    }

    Set *set = (Set *)[NSEntityDescription insertNewObjectForEntityForName:@"Set" inManagedObjectContext:managedObjectContext];
    set.weight = [NSNumber numberWithFloat:weightSelected2];
    set.reps = [NSNumber numberWithInt:repSelected];
    set.timeStamp = self.picker.date;
    [self.exercise addSetsObject:set];

    NSError *error = nil;
    if (![managedObjectContext save:&error]) 
    {
        // Handle the error.
    }
    NSLog(@"error: %@", error);
    self.fetchedResultsController = nil; 
    [setsTableView reloadData];
}

I have an entity Session. In my view, entity Exercise may be added to Session.

Before I save, I want to check if there are any relationships with Session, so if not, I will delete the object before saving it.

Can anyone tell me how to do this?

Edit:

- (void)createSession
{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit;
    NSDateComponents *dateComponentsForToday = [calendar components:unitFlags fromDate:self.picker.date];
    [dateComponentsForToday setHour:0];
    [dateComponentsForToday setMinute:0];
    [dateComponentsForToday setSecond:0];
    NSDate *targetDateBegins = [calendar dateFromComponents:dateComponentsForToday]; 
    NSDate *targetDateEnds = [targetDateBegins dateByAddingTimeInterval:(60 * 60 * 24 - 1)];

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    [fetchRequest setPredicate:[NSPredicate predicateWithFormat: @"(timeStamp >= %@ && timeStamp <= %@)", targetDateBegins, targetDateEnds]];
    [fetchRequest setEntity:[NSEntityDescription entityForName:@"Session" inManagedObjectContext:managedObjectContext]];
    NSLog(@"timeStamp >= %@ && timeStamp <= %@", targetDateBegins, targetDateEnds);

    NSError *error = nil;
    NSArray *results = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    NSLog(@"Fetch error: %@", error);

    if ([results count])
    {
        session = (Session *)[results objectAtIndex:0];
    }
    else
    {
        session = (Session *)[NSEntityDescription insertNewObjectForEntityForName:@"Session" inManagedObjectContext:managedObjectContext];
        session.timeStamp = self.picker.date;
    }

    NSSet *filteredExercisesFromSession = [session.exercises filteredSetUsingPredicate:[NSPredicate predicateWithFormat: @"name == %@",selectedExerciseName]];
    if ([filteredExercisesFromSession count] > 0)
    {
        self.exercise = [filteredExercisesFromSession anyObject];
    }

    [fetchRequest release];
    self.fetchedResultsController = nil;
    [setsTableView reloadData];
}

-(IBAction)createSet
{    
    NSSet *filteredExercisesFromSession = [session.exercises filteredSetUsingPredicate:[NSPredicate predicateWithFormat: @"name == %@",selectedExerciseName]];

    if ([filteredExercisesFromSession count] > 0)
    {
        self.exercise = [filteredExercisesFromSession anyObject];
    }
    else
    {
        NSLog(@"exercise does not already exist");
        self.exercise = (Exercise *)[NSEntityDescription insertNewObjectForEntityForName:@"Exercise" inManagedObjectContext:managedObjectContext];
        self.exercise.name = selectedExerciseName;
        self.exercise.muscleGroup = muscleName;
        [session addExercisesObject:exercise];
    }

    Set *set = (Set *)[NSEntityDescription insertNewObjectForEntityForName:@"Set" inManagedObjectContext:managedObjectContext];
    set.weight = [NSNumber numberWithFloat:weightSelected2];
    set.reps = [NSNumber numberWithInt:repSelected];
    set.timeStamp = self.picker.date;
    [self.exercise addSetsObject:set];

    NSError *error = nil;
    if (![managedObjectContext save:&error]) 
    {
        // Handle the error.
    }
    NSLog(@"error: %@", error);
    self.fetchedResultsController = nil; 
    [setsTableView reloadData];
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不…忘初心 2024-11-18 16:42:07

编辑多么不清楚的问题......!下次请先贴出代码。

您的 NSPredicate 可能是错误的,请尝试以下操作:

[NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)",
                                   startDate, endDate];

ENDOFEDIT


只需获取对象以确保它存在或不存在。

如果您的关系是Session 1->n Exercise,那么您应该有一个反向关系,例如myExercise.session,以便轻松检查(获取)。或者您可以只使用普通的 NSFetchRequest...

另请注意,CoreData 中有“级联”删除功能,但我怀疑它对您的(子实体)情况有帮助。

没有更多的代码/细节,很难弄清楚你的问题是什么以及如何解决它。

EDIT What an unclear question...! Next time please post code first.

Your NSPredicate might be wrong, try this :

[NSPredicate predicateWithFormat:@"(date >= %@) AND (date <= %@)",
                                   startDate, endDate];

ENDOFEDIT


Just fetch the object to ensure it exist or not.

If your relation is Session 1->n Exercise then you should have an inverse relationship like myExercise.session to check (fetch) easily. Or you can just use plain NSFetchRequest...

Also note that there are 'cascade' delete facilities in CoreData, but I doubt It could help in your (child entity) case.

W/o any more code/details it is hard to figure what's your issue and how to solve it.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文