【问题标题】:adjust order of one array based on the order of another array that was sorted根据已排序的另一个数组的顺序调整一个数组的顺序
【发布时间】:2016-08-09 01:10:22
【问题描述】:

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

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;

}
}

【问题讨论】:

  • 我认为你最好使用一个 single 字典数组,每个字典都包含一个 username 和一个 score(或者可能是一个自定义类)。您可以使用自定义块对它们进行排序,该块比较每个字典的 score 条目,并且您可以使用相同的数组作为两个表的数据源(为每个表选择不同的条目)。
  • 酷听起来不错,你能提供一个代码示例吗?我想我有一个粗略的想法,所以如果没有也不要担心
  • 如果您知道如何使用NSDictionary-objectForKey:-setObject:forKey:NSArray-sortedArrayUsingComparator:,那就很简单了。
  • 非常感谢...是的..只是需要复习
  • 如果你愿意,你可以发表你的评论作为答案,第一个

标签: ios objective-c arrays sorting indexing


【解决方案1】:

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

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

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
     }
}

【讨论】:

  • 对于self.entries = [self.entries sortedArrayUsingComparator:^NSComparisonResult(NSDictionary* a, NSDictionary* b) { NSDate *first = [a objectForKey:"score"]; NSDate *second = [b objectForKey:"score"]; return [first compare:second]; }]; 什么是a 和b?我看到它们是参数......但是你在那个块中使用它们。我创建了一个可变的字典数组,就像你说的那样,只是不确定比较发生了什么……还有 NSDate。
  • 我的代码正在组织分数(我在我的代码中称它们为匹配项)10、3、4 而不是 10、4、3...我发布了我所做的
【解决方案2】:

感谢 NicolasMiari 帮助我解决了大部分问题。比较的方式发生了一些奇怪的事情——它产生了一个未排序的结果。这是我的排序方式:

NSSortDescriptor * descriptor = [[NSSortDescriptor alloc] initWithKey:@"matches" ascending:NO selector:@selector(localizedStandardCompare:)];
NSArray *entrieshold = [entries sortedArrayUsingDescriptors:@[descriptor]];
transfer = [entrieshold copy];

似乎对我来说最重要的是selector:@selector(localizedStandardCompare:)。我对copy 的使用也可能很重要……但我不这么认为。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2011-07-06
    • 2021-08-12
    • 2019-08-04
    • 1970-01-01
    • 2015-06-08
    • 1970-01-01
    相关资源
    最近更新 更多