在UITableView中汇总类似行的最佳方法是什么,如Phone's's Offnts选项卡。我正在使用Core Data,并且当前按照NSManagedObject中的“timestamp”字段按时间顺序显示数据。 iPhone Recents表将行组合成一行以压缩冗余数据。
实现这一目标的最佳方法是什么?
答案 0 :(得分:0)
我确信Apple在代码中有一些更简单的方式,但这就是我想出来的。我在NSArray
方法中实例化了1 viewDidLoad
(包含一些原始数据),然后在.h中声明为属性(并且懒惰地实例化)的2 NSMutableArray
文件。这是我的代码。
·H
@interface RollUpTableViewController : UITableViewController
@property (strong, nonatomic) IBOutlet UITableView *rollUpTableView;
@property (strong, nonatomic) NSMutableArray *names;
@property (strong, nonatomic) NSMutableArray *countOfNames;
@end
的.m
-(NSMutableArray *)names{
if(!_names) _names = [[NSMutableArray alloc]init];
return _names;
}
-(NSMutableArray *)countOfNames{
if (!_countOfNames) _countOfNames = [[NSMutableArray alloc] init];
return _countOfNames;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSArray *rawData = [[NSArray alloc] initWithObjects:@"Jack", @"Jill", @"Jill", @"Ryan", @"Bill", @"Ryan", @"Ryan", @"Ryan", @"Steve", @"Katie", @"Jill", @"Ryan", @"Ryan", nil];
int countOfLikeNames = 0;
int i=0;
for (i = 0; i < [rawData count]; i++){
if (i == 0) {
//Putting the first name in the names NSMutableArray no matter what
[self.names addObject:[rawData objectAtIndex:i]];
countOfLikeNames = countOfLikeNames + 1;
} else {
//Checking if the current name is the same as the previous
if ([rawData objectAtIndex:i] == [rawData objectAtIndex:(i-1)]) {
countOfLikeNames = countOfLikeNames + 1;
} else {
//Once it runs into a difference in names, add the final count to the countOfNames NSMutableArray
[self.countOfNames addObject:[NSNumber numberWithInt:countOfLikeNames]];
//Starting the count over
countOfLikeNames = 1;
//Adding the next name
[self.names addObject:[rawData objectAtIndex:i]];
}
}
//if the for loop is on its last iteration, add what will be the last object for countOfNames
if (i == ([rawData count] - 1)) {
[self.countOfNames addObject:[NSNumber numberWithInt:countOfLikeNames]];
}
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [self.names count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.textLabel.text = [self.names objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [[self.countOfNames objectAtIndex:indexPath.row] stringValue];
return cell;
}
@end
我有点懒,只是在UITableViewCell上使用了Apple内置的“Right Detail”风格,这就是原始数据的结果。
您必须比较CoreData中的时间戳,但希望这可以帮助您理解这个概念。