我的核心数据模型:
Contact
=======
name
phone number (unique)
我需要显示具有以下条件的联系人的表格视图:
如果有多个联系人使用相同的名称 - 显示姓名+号码 否则 - 仅显示名称
例如,如果我的核心数据联系人是:
Michael, 11112221
Jon, 33438282
Jon, 72727272
Lisa, 99939393
我的表格视图应该出现:
Jon (33438282)
Jon (72727272)
Lisa
Michael
目前我正在使用以下NSFetchRequest来显示联系人列表:
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Contact"];
request.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)]];
request.fetchBatchSize = 20;
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:context
sectionNameKeyPath:@"nameFirstLetter"
cacheName:nil];
我正在寻找最有效的方法知道哪个名称出现多次,所以我可以在名称旁边显示数字。
答案 0 :(得分:2)
如果您使用NSSQLiteStoreType
作为持久存储,则可以使用NSExpression获取重复项:
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Contact" inManagedObjectContext:self.managedObjectContext];
NSAttributeDescription *nameDesc = [entity.attributesByName objectForKey:@"name"];
NSExpression *keyPathExpression = [NSExpression expressionForKeyPath:@"name"];
NSExpression *countExpression = [NSExpression expressionForFunction:@"count:" arguments:@[keyPathExpression]];
NSExpressionDescription *expressionDescription = [[NSExpressionDescription alloc] init];
[expressionDescription setName: @"count"];
[expressionDescription setExpression: countExpression];
[expressionDescription setExpressionResultType: NSInteger32AttributeType];
NSError *error = nil;
NSFetchRequest *fetch = [NSFetchRequest fetchRequestWithEntityName:@"Contact"];
[fetch setPropertiesToFetch:@[nameDesc, expressionDescription]];
[fetch setPropertiesToGroupBy:@[nameDesc]];
[fetch setResultType:NSDictionaryResultType];
NSArray *results = [self.managedObjectContext executeFetchRequest:fetch error:&error];
NSArray *duplicates = [results filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"count > 1"]];
NSArray *duplicateNames = [duplicates valueForKeyPath:@"name"];
duplicateNames
包含名称在数据库中多次出现的联系人姓名。因此,只要在表视图中显示联系人,只需查询duplicateNames
数组以检查实际联系人是否重复。
答案 1 :(得分:1)
最简单方式,如果您只想修改显示,我会修改tableView:cellForRowAt...
以检查当前人员上方和下方人员的姓名
:
- tableView:cellForRowAtIndexPath:(id)path {
....
Person *prior = ...
Person *next = ...
if(prior.name == current.name || next.name == current.name) {
//show name+number
}
}