使用 NSExpression 组合实体并返回 NSArray 或 NSArray 元素
Posted
技术标签:
【中文标题】使用 NSExpression 组合实体并返回 NSArray 或 NSArray 元素【英文标题】:Using NSExpression to combine entities and return an NSArray or NSArray elements 【发布时间】:2013-04-09 03:06:22 【问题描述】:我希望我的UITableViewController
的NSFetchRequest
根据特定属性对相似的记录(实体)进行分组。我目前做了一个两步过程,但我相信可能有办法使用+ (NSExpression *)expressionForAggregate:(NSArray *)collection
。
有人可以帮助编写适当的代码吗?
这是我的两步过程的代码,它返回一个数组的数组:
+(NSArray *)getTopQforDogByProgram2:(Dog *)dog
inProgram:(RunProgramTypes)programType
inManagedContext:(NSManagedObjectContext *)context
NSString *searchString;
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Run"];
request.predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"dog.callName = '%@'",dog.callName]];
NSSortDescriptor *classSortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"runClass" ascending:NO];
request.sortDescriptors = [NSArray arrayWithObject:classSortDescriptor];
NSError *error = nil;
NSArray *dataArray = [context executeFetchRequest:request error:&error];
NSMutableArray *returnArray = [[NSMutableArray alloc] init];
if ( [dataArray count] > 0 )
NSMutableArray *pointArray = [[NSMutableArray alloc] init];
for ( Run *run in dataArray )
if ( ! [returnArray count] )
[pointArray addObject:run];
[returnArray addObject:pointArray];
else
BOOL wasSame = FALSE;
for ( NSMutableArray *cmpArray in returnArray )
Run *cmpRun = [cmpArray lastObject];
if ( cmpRun.runClass == run.runClass )
[cmpArray addObject:run];
wasSame = TRUE;
break;
if ( ! wasSame )
pointArray = [[NSMutableArray alloc] init];
[pointArray addObject:run];
[returnArray addObject:pointArray];
return returnArray;
【问题讨论】:
【参考方案1】:您可以像这样使用获取结果控制器为您进行切片:
NSFetchedResultsController* controller = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:context
sectionNameKeyPath:@"runClass"
cacheName:nil];
NSMutableArray* sections = [[NSMutableArray alloc] initWithCapacity:[controller sections] count];
for (id<NSFetchedResultsSectionInfo> section in [controller sections])
NSMutableArray* sectionCopy = [NSMutableArray arrayWithArray:[section objects]];
[sections addObject:sectionCopy];
或者自己做:(假设结果按runClass
排序)
NSMutableArray* sections = [NSMutableArray new];
NSMutableArray* currentSection = [NSMutableArray new];
for (Run* run in dataArray)
Run* lastObject = (Run*)[currentSection lastObject];
if (lastObject && (run.runClass == lastObject.runClass))
currentSection = [NSMutableArray new];
[sections addObject:currentSection];
[currentSection addObject:run];
【讨论】:
以上是关于使用 NSExpression 组合实体并返回 NSArray 或 NSArray 元素的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 NSExpression 使用自定义函数设置 NSFetchRequest propertiesToFetch
NSExpression 尊重子查询 NSPredicate