【发布时间】:2014-04-28 14:35:54
【问题描述】:
我最近一天一直在研究这个问题,所以我认为是时候提出这个问题了。
我在 CoreData 中创建了一个一对多的自引用关系来存储联系人并对这些联系人进行分组。
没有父级的联系人实际上持有其子级的“部分名称”。
Section name (object without parent)
-------------------------------------
Contact 1
Contact 2
保存对象的代码(简化):
//Create Section
section = [NSEntityDescription insertNewObjectForEntityForName:@"Contact" inManagedObjectContext:_managedObjectContext];
[section setValue:self.sectionField.text forKey:@"name"];
[section setValue:nil forKey:@"parent"];
[_managedObjectContext save:&error];
//Create contact
NSManagedObject *newContact = [NSEntityDescription
insertNewObjectForEntityForName:@"Contact"
inManagedObjectContext:_managedObjectContext];
[newContact setValue:self.nameField.text forKey:@"name"];
[newContact setValue:self.numberField.text forKey:@"data"];
[newContact setValue:[NSString stringWithFormat:@"%@",[LoginController getUser][@"id"]] forKey:@"user_id"];
[newContact setValue:section forKey:@"parent"];
表格视图控制器:
在viewWilAppear 中,我获取表视图的所有“父”对象(=sections)并将它们分配给self.sections 属性。
//In viewWillAppear I get all "parent" objects
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:_managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDescription];
// Set predicate
[request setRelationshipKeyPathsForPrefetching: [NSArray arrayWithObject:@"children"]];
NSPredicate *predicate = [NSPredicate predicateWithFormat: @"(parent == nil) AND (children.@count > 0)"];
[request setPredicate:predicate];
self.sections = (NSMutableArray *)[_managedObjectContext executeFetchRequest:request error:nil];
然后在 cellForRowAtIndexPath 中,我尝试在 indexPath.section 的父级中检索索引在 indexPath.row 的子级。
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
[cell setSelectionStyle:UITableViewCellSelectionStyleBlue];
Contact * section = [self.sections objectAtIndex:indexPath.section];
NSArray * contacts = [section.children allObjects];
Contact * contact = [contacts objectAtIndex:indexPath.row];
NSLog(@"contact %@", contact.name);
[cell.textLabel setText:contact.name];
[cell.detailTextLabel setText:contact.data];
UIImageView *call = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"Call"]];
[cell setAccessoryView:call];
return cell;
联系人的姓名不会显示,我在这里有点绝望。还有其他见解吗?
【问题讨论】:
-
只是对您的设计的建议。为联系人及其关系创建两个表。自我引用可能会导致内存问题。
-
好的调用,将使用该实现作为良好实践。
标签: ios iphone core-data relationship