【问题标题】:Sectioning every 3 rows in NSFetchedResultsController在 NSFetchedResultsController 中每 3 行分割一次
【发布时间】:2012-08-26 10:43:44
【问题描述】:

我想要做的是每 x 行创建 NSFetchedResultsController 部分。

我尝试过创建一个瞬态属性,它会根据它的索引给出它的部分,如下所示:

- (NSNumber*)section
{
    [self willAccessValueForKey:@"section"];
    NSManagedObjectContext* context = [(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
    NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Animal"];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES]]];
    NSArray* array = [context executeFetchRequest:fetchRequest error:NULL];
    int order = [array indexOfObject:self];
    NSNumber *tmpValue = [NSNumber numberWithInt:order / 3];
    [self didAccessValueForKey:@"section"];
    return tmpValue;
}

并通过在每个对象上触发此功能使视图控制器刷新部分:

-(void)refreshSection
{
    NSManagedObjectContext* context = [(AppDelegate*)[[UIApplication sharedApplication] delegate] managedObjectContext];
    NSFetchRequest* fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Animal"];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"title" ascending:YES]]];
    NSArray* array = [context executeFetchRequest:fetchRequest error:NULL];
    int order = [array indexOfObject:self];
   [self setSection:[NSNumber numberWithInt:order / 3]];
}

此解决方案有效,但对大量对象无效。

基本上,我想要实现的是:

第 0 节:
一个
b
d
第 1 部分:
e

如果我添加了 c :

第 0 节:
一个
b
c
第 1 部分:
d
e

还有其他更优雅的方法吗?

谢谢..

【问题讨论】:

    标签: objective-c ios cocoa-touch core-data


    【解决方案1】:

    如果您在瞬态属性中进行提取,性能显然会受到负面影响。

    不要担心这个瞬态属性。相反,在方法 numberOfSection 中,只返回对象的数量除以 3 并向上取整。

    对于部分中的行数,只需返回 3,但请记住,最后一部分将是对象数除以 3 的余数。

    当你添加一个对象时,记得更新表,那些方法会被再次调用。

    【讨论】:

    • 您的方法有效,在发生任何更改时重新加载表视图的情况下,但是如果我想使用更新块为添加或删除设置动画,则很难在 fetchedresultscontroller 之间转换索引路径和表格视图,我还必须管理节的插入和删除,因为从 fetchedresultscontroller 的角度来看,只有一个节。这就是为什么我选择直接来自获取的控制器的解决方案。
    • 你说很难,不是不可能?有时当您有特殊要求时,您需要特殊的解决方案,即使它并不优雅。如果性能是必须的,那就没有太多选择了。
    猜你喜欢
    • 1970-01-01
    • 2017-08-29
    • 1970-01-01
    • 1970-01-01
    • 2013-07-27
    • 2016-11-07
    • 2010-12-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多