1对1关系核心数据iOS

时间:2012-03-08 06:41:02

标签: iphone ios core-data entity-relationship iphonecoredatarecipes

我有两个实体:登录(用户ID,密码)和信息(标题,信息)。 现在它们之间存在1比1的关系。 我需要在数据库中添加一些对用户唯一的信息。

我的代码如下:

    Login *information = [NSEntityDescription insertNewObjectForEntityForName:@"Login"
                                                      inManagedObjectContext:self.managedObjectContext];

    information.information.title = informationTitleTextView.text;
    information.information.info_1 = information1textview.text;
    information.information.info_2 = information2textview.text;

    [self.managedObjectContext save:nil];  // write to database

    [self.delegate savebuttontapped:self];

但它没有工作。我不知道,我做错了什么?我们将不胜感激。

1 个答案:

答案 0 :(得分:1)

您尚未向上下文添加Information的实例。试试这个:

Login *login = [NSEntityDescription insertNewObjectForEntityForName:@"Login" inManagedObjectContext:self.managedObjectContext];
Information *information = [NSEntityDescription insertNewObjectForEntityForName:@"Information" inManagedObjectContext:self.managedObjectContext];

login.information = information;
login.information.title = informationTitleTextView.text;
//...and so on...

当然,如果您要根据其属性获取Login对象,您可能希望在这些属性中实际存储某些内容:

login.userId = theUserId;
login.password = thePassword;

在将来的某个时刻,您可能只想获取符合条件的Login对象。完成后,您可以毫无困难地获取相关的信息对象:

NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Login"
    inManagedObjectContext:managedObjectContext];
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"userId like %@ AND password like %@", theUserId, thePassword];
[request setPredicate:predicate];
NSError *err = nil;
NSArray *matchingLogins = [self.managedObjectContext executeFetchRequest:request error:&err];
int count = [matchingLogins count];
if (count != 1) {
    NSLog(@"Houston, we have a problem.");
}
Login *login = [matchingLogins objectAtIndex:0];
Information *info = login.information; // Notice: no separate fetch needed