【问题标题】:iOS - Stuck on numberOfRowsInSection: with multiple sectionsiOS - 卡在 numberOfRowsInSection:有多个部分
【发布时间】:2014-08-22 14:04:37
【问题描述】:

我需要一些关于numberOfRowsInSection: 方法的帮助。实际上,我正在寻找一种更动态的方式来设置行数。因为在我的应用程序中可以创建sections(任意数量,它们由 NSUserDafults 存储为 NSMutableArray)我认为这样的东西编码太硬,因此完全错误,因为我不知道有多少部分用户将创建。

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return ...
    }
    if (section == n) {
        return ...
    }        
}

然后,我正在努力如何在这些部分中显示NSManagedObject。我的意思是,当用户创建NSManagedObject 时,他设置了它的section 属性。我希望NSManagedObject 将显示在右侧section

P.S. NSManagedObjects 存储在 NSMutableArray 中。

【问题讨论】:

    标签: ios objective-c uitableview nsmanagedobject sections


    【解决方案1】:

    您可以使用NSPredicate 过滤您保留NSManagedObjectsNSMutableArray,以返回特定部分中的所有对象。我不知道你的类型section property,但我们假设它是NSInteger,这样我们就可以轻松地使用来自

    的section param
    - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
    

    然后在这个方法中你可以过滤 myArray 并计算它的对象:

    [[self.myArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"section == %d",section]] count];
    

    【讨论】:

      【解决方案2】:

      最简单的方法是将每个部分的托管对象放入单独的数组中,然后创建这些数组的数组。

      所以如果你像这样划分它们:

      NSArray *sections - @[@[obj1, obj2, obj3],
                            @[obj4, obj5, obj6],
                            ...];
      

      您可以按如下方式实现numberOfRowsInSection

      - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
          return [sections[section] count];
      }
      

      【讨论】:

        猜你喜欢
        • 2016-07-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多