0

我有一个名为 Application 的核心数据实体,它可以将多个屏幕截图作为一组添加到其中。每个屏幕截图都有一个“订单”属性,我希望用它来仅从每组中提取第一个屏幕截图。

下面是我目前正在使用的代码,但也许有一些更简单/更有效的方法可以用来从 -to many 关系中提取具有特定顺序的屏幕截图?

   if(managedObject.screenshots.count>0)
        {

            //search for a screenshot 
            NSMutableArray* predicatesArray = [[NSMutableArray alloc] initWithCapacity:2];
            [predicatesArray addObject:
            [NSPredicate predicateWithFormat:@"SELF.order == %d",0]];
            [predicatesArray addObject:
            [NSPredicate predicateWithFormat:@"SELF.application == %@",managedObject]];

            NSPredicate* compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates: predicatesArray];

            NSFetchRequest *firstScreenshot = [NSFetchRequest fetchRequestWithEntityName:@"Screenshot"];
            firstScreenshot.predicate = compoundPredicate;

            NSError* error;
            NSArray* results =  [managedObject.managedObjectContext executeFetchRequest:firstScreenshot error:&error];

            if(error)
            {
                DLog(@"%@",[error localizedDescription]);
            }

            //if we got a result
            if(results.count>0)
            {
                Screenshot* screenshot = [results objectAtIndex:0];
                cell.screenshot.image = [UIImage imageWithData:screenshot.image];
            }else
            {
              cell.screenshot.image = [UIImage imageNamed:@"blank1.png"];  
            }

        }
4

0 回答 0