ios - 根据已排序的另一个数组的顺序调整一个数组的顺序

标签 ios objective-c arrays sorting indexing

我有两张表,一张用于用户名,一张用于分数。我用两个数组填充这些表。表格需要根据分数降序排列。我用其中的分数对数组进行排序,但我不确定如何安排用户名以坚持他们的分数,它们在一个单独的数组中,并且是一个与分数表分开的表。这是我的代码:

dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
sortedFirstArray = [dictionary allKeys];
sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
sortedSecondArray = [sortedSecondArray sortedArrayUsingSelector: @selector(compare:)];

我需要 sortedFirstArray 值按照它们在每个数组中的顺序与它们各自的 sortedSecondArray 值保持一致。

更新

我的代码尝试进行排序:

PFQuery *query = [PFQuery queryWithClassName:@"_User"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (!error) {
                entries = [NSMutableArray new];
                for (PFObject *object in objects) {
                    NSLog(@"%@", object.objectId);
                    [tableData addObject:[object valueForKey:@"username"]];
                    [matchesForUser addObject:[object valueForKey:@"matches"]];

                    NSMutableDictionary* entry = [NSMutableDictionary new];

                    entry[@"username"] = [object valueForKey:@"username"];
                    entry[@"matches"] = [object valueForKey:@"matches"];

                    [entries addObject:entry];

                    //transfer = entries;
                }
                transfer = [entries sortedArrayUsingComparator:^NSComparisonResult(NSDictionary* a, NSDictionary* b) {
                    NSDate *first  = [a objectForKey:@"matches"];
                    NSDate *second = [b objectForKey:@"matches"];
                    NSLog(first);
                    NSLog(second);
                    return [first compare:second];
                }];
            //dictionary = [NSDictionary dictionaryWithObjects:matchesForUser forKeys:tableData];
            //sortedFirstArray = [dictionary allKeys];
            //sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];
            //sortedSecondArray = [sortedSecondArray sortedArrayUsingSelector: @selector(compare:)];
            [_tableView reloadData];
            [_tableViewScore reloadData];

        }else{
            NSLog([error description]);
        }

        NSLog(@"***tabledata***");
        NSLog([NSString stringWithFormat:@"%lu", (unsigned long)[tableData count]]);
        NSLog(@"***matchesdata***");
        NSLog([NSString stringWithFormat:@"%lu", (unsigned long)[matchesForUser count]]);
    });
}];
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
if(tableView.tag == 1) {
    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0];
    cell.textLabel.textColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
    cell.backgroundColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
    cell.layoutMargins = UIEdgeInsetsZero;
    cell.preservesSuperviewLayoutMargins = NO;

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    UILabel *contentV = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 230, 44)];
    contentV.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0];
    contentV.textColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
    contentV.backgroundColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];

    cell.contentView.layoutMargins = UIEdgeInsetsZero;

    NSString *username2 = [[transfer objectAtIndex:indexPath.row] valueForKey:@"username"];

    NSLog(@"***username***");
    NSLog(username2);

    contentV.text = username2;
    [cell.contentView addSubview:contentV];

    return cell;
}
else {
    static NSString *simpleTableIdentifier = @"SimpleTableItem";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:simpleTableIdentifier];
    cell.textLabel.font = [UIFont fontWithName:@"HelveticaNeue-Bold" size:16.0];
    cell.textLabel.textColor = [UIColor colorWithRed:153.0f/255.0f green:211.0f/255.0f blue:212.0f/255.0f alpha:1.0f];
    cell.backgroundColor = [UIColor colorWithRed:218.0f/255.0f green:247.0f/255.0f blue:220.0f/255.0f alpha:1.0f];
    cell.textLabel.textAlignment = NSTextAlignmentCenter;

    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:simpleTableIdentifier];
    }

    NSString *matchAmount = [[transfer objectAtIndex:indexPath.row] valueForKey:@"matches"];
    NSLog(@"***matchamount***");
    NSLog(matchAmount);

    cell.textLabel.text = matchAmount;

    return cell;

}
}

最佳答案

与其拥有两个单独的数组并直接对其中一个进行排序并尝试找出另一个数组的哪些条目对应于已排序数组中的哪些条目,不如将两个数组的成对条目放在一起一个实体(字典或自定义类的实例),并将它们分组到您的(单个)数组中:

实际的属性名称等会因您的代码而异,但总体思路是这样的:

self.entries = [NSMutableArray new];

for (int i=0; i < userNameArray.count; i++){

    NSMutableDictionary* entry = [NSMutableDictionary new];

    entry["userName"] = [userNameArray objectAtIndex: i];
    entry["score"   ] = [scoreArray objectAtIndex: i]; 
    // ^ TODO: Make sure scoreArray has at least as many elements 
    // as userNameArray!

    [self.entries addObject: entry];
}

self.entries = [self.entries sortedArrayUsingComparator:^NSComparisonResult(NSDictionary* a, NSDictionary* b) {
    NSDate *first  = [a objectForKey:"score"];
    NSDate *second = [b objectForKey:"score"];
    return [first compare:second];
}];

// (...)

UITableViewCell* tableView:(UITableView*) tableView cellForRowAtIndexPath:(NSIndexPath}) indexPath
{
    NSDictionary* entry = [self.entries objectAtIndex: indexPath.row];

    if (tableView == self.userNameTableView) {
         // (dequeue user cell...)

         cell.titleLabel.text = [entry objectForKey: "userName"];
         return cell
     }
     else{
         // (dequeue score cell...)

         cell.titleLabel.text = [entry objectForKey: "score"];
         return cell
     }
}

关于ios - 根据已排序的另一个数组的顺序调整一个数组的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38840565/

相关文章:

java - 我们得到了二维数组,arr (n)(n)。 e 选择任意索引,任务是计算周围元素的最小值和最大值

iphone - 在uiview上画直线

objective-c - 使用 NSDateComponents : changing year 获取一周的第一天

iOS:当应用程序被didEnterRegion唤醒时,如何启动UpdatingLocation?

iphone - iOS NSRangeException、索引越界、NSMutable 数组

arrays - 即使在 slice 和变异之后,为什么/如何保留其初始化值?

ios - 如何从 CGPoint 和 CGSize 创建 CGRect?

ios - 社交分享 Cordova 插件

ios - 一些 uitableviewcell 在我滚动 iPhone 之前不会显示所有数据

c++ - cin.getline() 正在删除我在 C++ 中输入的第一个让步