我要只显示部分项目在一个数组中,但不知道该怎么做。
这是我目前显示数组中所有对象的代码:
@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;
}
所以我只想显示 30 个中的 5 个 我创建的那个数组中的叶子对象,而不是全部显示。有没有办法做到这一点?
(我正在使用 API 将项目拉入数组)
感谢您的帮助,将发布所需的任何特定代码或其他信息!
编辑
根据请求添加:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
Spring *spring = [springs objectAtIndex:section];
return spring.leafs.count;
}
我正在使用 RestKit 进行对象映射。
最佳答案
使用[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:
中复制。委托(delegate)方法,否则您的应用程序将引发异常。
关于ios - 仅显示 Array 中的部分对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16470446/