我Coredata
第一次使用,我正在为实体设置一些值,从userinfo
实体中获取一些值usergroups
。
在执行此过程时,我的应用程序崩溃说:
'以前没有为其主键字段分配对象 ID 的项目,用于获取核心数据对象的永久 ID。在调用保存 managedObjectContext 之前,一定要分配一个对象 ID。
这看起来像
[newManagedObject setValue:[newManagedObject assignObjectId] forKey:[newManagedObject
primaryKeyField]]
. 有问题的项目是:
<Userinfo: 0x10695b30> (entity: Userinfo; id: 0x10695b70 <x-coredata://18875EDC-D300-4D63-90FC-181B2487599D-3229-000024DF842CC304/Userinfo/tA6216695-816F-4379-B24C-984AAFD1A8342>; data:
// 用于读取值和修改
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Userinfo" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSPredicate *datapredicate = [NSPredicate predicateWithFormat:@"username == %@",usermobileNumber];
[fetchRequest setPredicate:datapredicate];
[context executeFetchRequest:fetchRequest onSuccess:^(NSArray *results){
NSLog(@"results %@",[results valueForKey:@"firstname"]);
userinfoObject = [results objectAtIndex:0];
NSLog(@"userinfo %@",userinfoObject);
// userinfoObject = [[Userinfo alloc]initWithEntity:[NSEntityDescription entityForName:@"Userinfo" inManagedObjectContext:context] insertIntoManagedObjectContext:context];
[userinfoObject setValue:[userinfoObject valueForKey:@"firstname"] forKey:@"firstname"];
[userinfoObject setValue:[userinfoObject valueForKey:@"lastname"] forKey:@"lastname"];
[userinfoObject setValue:[userinfoObject valueForKey:@"email"] forKey:@"email"];
[userinfoObject setValue:[userinfoObject valueForKey:@"zipcode"] forKey:@"zipcode"];
[userinfoObject setValue:[userinfoObject valueForKey:@"password"] forKey:@"password"];
[userinfoObject setValue:[userinfoObject valueForKey:@"dateofbirth"] forKey:@"dateofbirth"];
[userinfoObject setValue:[userinfoObject valueForKey:@"username"] forKey:@"username"];
[userinfoObject setValue:[userinfoObject valueForKey:@"salutation"] forKey:@"salutation"];
// [userinfoObject setValue:[userinfoObject assignObjectId] forKey:[userinfoObject primaryKeyField]];
// 添加值
Usergroups *userGroupsObject = [NSEntityDescription insertNewObjectForEntityForName:@"Usergroups" inManagedObjectContext:context];
[userGroupsObject setValue:contactObject.strGroupName forKey:@"groupname"];
[userGroupsObject setValue:[contactsStack objectAtIndex:i] forKey:@"mobile_contacts"];
[userGroupsObject setValue:usermobileNumber forKey:@"mobile_number"];
[userGroupsObject setValue:[userGroupsObject assignObjectId] forKey:[userGroupsObject primaryKeyField]];
NSError *error = nil;
if (![context saveAndWait:&error]) {
NSLog(@"There was an error! %@", error);
}
else {
NSLog(@"You created Usergroup object!");
}
[userinfoObject addUsergroupsObject:userGroupsObject];