2013-05-09 41 views
1

我想只显示数组中的某些项目,但无法弄清楚如何去做。仅显示阵列中的部分对象

这是代码我有目前显示阵列中的所有对象:

@property (strong, nonatomic) NSArray *springs; 
@property (strong, nonatomic) NSMutableArray *leafs; 


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
    static NSString *CellIdentifier = @"standardCell"; 
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; 

    Spring *spring = [springs objectAtIndex:indexPath.section]; // 13 objects 
    Leaf *leaf = [spring.leafs objectAtIndex:indexPath.row]; // 30 objects 

    cell.textLabel.text = league.shortName; 
    return cell; 
} 

所以我想只显示5从阵列我创造了30个叶对象,而不是表现他们全部。有没有办法做到这一点?

(我使用一个API来拉项目进入阵列)

感谢您的帮助,将发布所需的任何特定的代码或其他信息!

EDIT 每个请求添加了:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    Spring *spring = [springs objectAtIndex:section]; 
    return spring.leafs.count; 
} 

我使用RestKit为对象的映射。

回答

2

使用[NSArray objectsAtIndexes:]reference)得到数组的一个子集。

Leaf *leaf = [spring.leafs objectAtIndex:indexPath.row]; 

// This will include objects 0-4: 
NSRange range = NSMakeRange(0, 5); 
NSArray *subset = [leaf objectsAtIndexes:[NSIndexSet indexSetWithIndexesInRange:range]]; 

只要将range调整为子集中想要的任何开始/长度即可。

编辑:当然这种方法中的任何子集逻辑也必须在numberOfRowsInSection:委托方法中复制,否则你的应用程序抛出异常。

+0

感谢您的回应,这使得很多意义,但是当我尝试它,'NSRange'行给了我一个错误,说:“初始化NSRange'与不兼容类型的表达式'NSRange' ...任何想法为什么? – Realinstomp 2013-05-09 20:44:51

+0

@Reez不,我不明白,你可以忘记'NSMakeRange()',并明确设置'range.location'和'range.length'。 – trojanfoe 2013-05-09 20:46:25

+0

我做了一个指针而不是struct,我的坏。现在我遇到的问题是,对于我的textLabel,我不能再使用'league.shortName',但是我不能只使用'subset.shortName',那么我会用什么?Thx再次 - – Realinstomp 2013-05-09 21:02:53

1

如何在您的tableView:numberOfRowsInSection,不返回完整的计数完整spring.leafs?例如,

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
    return 5; 
} 

你是不是想偷懒加载它们,还是它们的其余部分只是没有关系吗?祝你好运。

+0

其余的都没关系。感谢您的回应!当我试图返回5时得到的是与消息'*** - [__ NSArrayM objectAtIndex:]:index 1 beyond bounds [0 .. 0]'' – Realinstomp 2013-05-09 20:37:08

+0

崩溃是数组是空的。检查你的方法在你填充数组的地方,看看它为什么没有被填充。 – 2013-05-09 20:44:18

+0

只是在黑暗中拍摄,是否将'leafs'实例化为NSMutableArray? – 2013-05-09 20:45:11