核心数据关系,如何从关系中插入和检索数据

时间:2016-09-01 15:25:50

标签: ios objective-c core-data

我是IOS开发的新手,在使用关系

时特别使用核心数据时遇到问题

我有以下关系 enter image description here

如您所见,我有树实体,我想要做的是在特定用户食用食物时将数据插入CredentialsFood实体

所以我试图使用以下代码插入

    // adding to credetialsFood Entity
NSManagedObjectContext *context1 = [appD managedObjectContext];
CredentialsFood *credentialsFood = (CredentialsFood *)        [NSEntityDescription insertNewObjectForEntityForName:@"CredentialsFood"   inManagedObjectContext:context1];
NSDate *currentDate = [NSDate date];
credentialsFood.toFood.food_id = item_id;
credentialsFood.toCred.email = @"123";
credentialsFood.date = currentDate;


// here's where the actual save happens,
if(![context1 save:&errorCoreData]){
    NSLog(@"Problem saving: %@",[error localizedDescription]);
}
else{
    NSLog(@"Food date Saved");
}

代码工作正常 但是在检索时我尝试例如获取所有CredentialsFood.date,其中Credentials.email = 123 我什么都没收到

我真的不知道我做错了这是要检索的代码

NSManagedObjectContext *context2 = [appD managedObjectContext];

NSEntityDescription *foodEntity =[NSEntityDescription entityForName:@"Credentials" inManagedObjectContext:context2];

NSFetchRequest *request = [[NSFetchRequest alloc]init];

NSError *error2 = nil;
NSString * userid =@"123";

NSPredicate *foodPredicate = [NSPredicate predicateWithFormat:@"(email contains[cd] %@)",userid];

[request setEntity:foodEntity];
[request setPredicate:foodPredicate];

NSManagedObject *matches = nil;
NSArray *objects = [context executeFetchRequest:request error:&error2];


if([objects count]== 0){
    NSLog (@"no matches found");

}
else {
    //NSLog(@"aasdasdad %@", objects);
    matches = [objects objectAtIndex:0];
    NSLog(@"bb %@",[matches valueForKey:@"name"]);
    NSLog(@"bb %@",[matches valueForKey:@"email"]);
    NSLog(@"bb %@",[matches valueForKey:@"password"]);
    //NSLog(@"hhhhhhhhhhhhhh %@",[matches valueForKey:@"credentails"]);

    NSMutableSet *query = [matches mutableSetValueForKey:@"credentails"];


    NSArray *financialData =[matches valueForKeyPath:@"credentails"];
    NSLog(@"%@",financialData);
    NSLog(@"%@",[financialData valueForKey:@"date"]);

的数据是核心数据内但是我不知道它正在执行的关系,食物实体被填充,并且也填充CredentialsFood

我也收到了警告 抽象实体食物没有孩子 抽象实体凭据没有子节点 抽象实体CredentialsFood没有孩子

提前致谢

1 个答案:

答案 0 :(得分:1)

首次创建对象时:

CredentialsFood *credentialsFood = (CredentialsFood *) [NSEntityDescription insertNewObjectForEntityForName:@"CredentialsFood" inManagedObjectContext:context1];
NSDate *currentDate = [NSDate date];
credentialsFood.toFood.food_id = item_id;
credentialsFood.toCred.email = @"123";

...您似乎没有为toFoodtoCred关系分配任何内容。相关对象不是自动创建的,因此这些属性将为零。在Objective-C中,当这些属性为nil时,运行此代码并不是错误,但代码无效。看起来您需要创建(或获取)FoodCredentials的实例,并将这些新对象分配给toFoodtoCred属性。