我将尝试使用核心数据的多个实体。
两个实体名称中的核心数据Student
和Detail
都具有反比关系。关系名称为Student -> Detail:detail
Detail -> Student:student
。
尝试从实体中获取记录并在表视图中显示。尝试多个代码,但无法获得结果。
第一个代码:
Detail *d;
NSMutableArray *arrObj = [[NSMutableArray alloc]init];
for(Student *tblObj in [d student]){
[arrObj addObject:tblObj];
}
NSLog(@"Your records related with tableA = %@",arrObj);
无法在数组中加载数据。
第二个代码:
NSArray* fetchResults = [_mainContext executeFetchRequest:fetchRequest error:nil];
for (int i; i > 1; i++) {
Student *tableAObject = fetchResults[i];
NSString * itemcode = tableAObject.detail.email;
NSLog(@"%@",itemcode);
}
无法显示记录。
第三种方式:NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *aEntity = [NSEntityDescription entityForName:@"Student" inManagedObjectContext:_mainContext];
[fetchRequest setEntity:aEntity];
NSString *relationshipKeyPath = @"detail"; // Set this to the name of the relationship on "SP" that points to the "Code" objects;
NSArray *keyPaths = [NSArray arrayWithObject:relationshipKeyPath];
[fetchRequest setRelationshipKeyPathsForPrefetching:keyPaths];
NSMutableArray *arrObj = [[NSMutableArray alloc]init];
for(Student *spObj in arrObj)
{
NSLog(@"description is %@",spObj.name);
Detail *codObj = spObj.detail;
NSLog(@"it has value %@",codObj);
NSLog(@" unique name is %@",codObj.email);
}
核心dta中插入数据的代码:
- (IBAction)submitData:(id)sender {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate manageObjectContext];
Student *student = (Student *)[NSEntityDescription insertNewObjectForEntityForName:@"Student" inManagedObjectContext:context];
student.name = _nameText.text;
student.number = _noText.text;
student.study = _studyText.text;
Detail *detail = (Detail *)[NSEntityDescription insertNewObjectForEntityForName:@"Detail" inManagedObjectContext:context];
detail.number = _noText.text;
detail.email = _emailText.text;
detail.address = _addressText.text;
detail.contact = _contactText.text;
student.detail = detail;
detail.student = student;
NSError *error = nil;
[context save:&error];
if (![context save:&error]) {
NSLog(@"error in adding data %@, %@", error, [error userInfo]);
abort();
}
}
如果您需要更多详细信息,请通知我。谢谢。
答案 0 :(得分:1)
您尝试过的前两种方法无法正常工作,因为没有与从核心数据中获取数据相关的代码。第三种方法是你没有执行你的获取请求。 以下是从核心数据中获取数据的方法。
NSFetchRequest *req = [[NSFetchRequest alloc] initWithEntityName:@"Student"];
NSError *error = nil;
NSArray *students = [context executeFetchRequest:req error:&error];
for (Student *stdObj in students)
{
//Student object
NSLog(@"Name %@",stdObj.name);
NSLog(@"Number %@",stdObj.number);
//Detail object related to student
Detail *detailObj = stdObj.detail;
NSLog(@"Email %@",detailObj.email);
NSLog(@"Address %@",detailObj.address);
}