【问题标题】:using a predicate with fetch without a tableView在没有 tableView 的情况下使用带有 fetch 的谓词
【发布时间】:2014-04-18 17:17:24
【问题描述】:

为了了解 Core Data,我正在制作一个测验应用程序,但它不使用表格视图。我在应用程序中植入了两个测验的数据。当用户单击视图上的按钮时,我想获取一个测验,具体取决于他/她按下的按钮,但我不确定我可以为谓词输入什么

       if ([sender.currentTitle isEqualToString:@"sports"]){

        NSError *error;
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Quizdata"
                                                  inManagedObjectContext:self.managedObjectContext];
        [fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(SELF = %@)", ????];  ///unsure what to put here
        [fetchRequest setPredicate:predicate];
        self.fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
        NSLog(@"fetched object %@", fetchedObjects);

    }else if ([sender.currentTitle isEqualToString:@"entertainment"]){
        NSLog(@"entertainment%@", sender.currentTitle);
    }

我有两个实体,例如 Quiz.h,我根据实体的属性为其创建了类

@dynamic quizId;
@dynamic name;
@dynamic quizData;

还有一个 QuizData.h 实体

@dynamic answer1;
@dynamic answer2;
@dynamic answer3;
@dynamic answer4;
@dynamic correctAnswer;
@dynamic question;
@dynamic score;
@dynamic unique;
@dynamic quiz;

我曾希望通过做类似于我在 Rails 中所做的事情来获取两个测验中的一个

Quizdata.where(quizId => 1)

是否可以仅以我的方式获取体育问题(即不使用表格视图)。我认为 tableView 可能很重要的原因是它会有对象 ID。我不知道如何让 CoreData 检索 quizId 1 的每个问题。

我以前用json导入过这样的数据

{ "question" : "Do you like basketball", "answer1": "yes", "answer2": "no", "answer3": "maybe", "answer4":"of course", "correctAnswer": "yes", "unique": "2", "name": "sportsquiz", "quizId": "1"},

然后用两个类插入保存

【问题讨论】:

    标签: ios core-data


    【解决方案1】:

    当然……

    我没有完全遵循您模型上的逻辑因为我没有看到 Quiz 和 QuizData 之间的关系。

    如果你有一个,你会在 Quiz 中有一个包含 QuizData 集合的 NSSet。您只需像这样执行 NSFetchRequest;

       NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
       NSEntityDescription *entity = [NSEntityDescription entityForName:@"Quiz" inManagedObjectContext:context];
       [fetchRequest setEntity:entity];
    
       NSPredicate *predicate = [NSPredicate predicateWithFormat:@"quizId >= %@", [NSNumber numberWithInt:1]];
       [fetchRequest setPredicate:predicate];
    
        NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
    

    FetchedObjects 将包含 quizId >= 1 的“测验”对象数组。如果您正确设置了关系,每个测验对象将包含 quizData 对象的集合。

    要记住的主要事情是Core Data 是一个对象图。因此,您可以将 quizData 对象添加到您的 Quiz 对象(而不是设置关系字段并将关系键添加到 Quiz 对象)。

    【讨论】:

      猜你喜欢
      • 2014-08-28
      • 2012-11-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-14
      • 2016-05-12
      • 2011-11-30
      相关资源
      最近更新 更多