按升序排列数组并删除 objective- c 中的重复值

Sort array in ascending order and remove duplicate values in objective- c

我有一个可水平和垂直滚动的 table。我从 Web 服务 (json) 获取 header 和第一列的数据。我想按升序对数据进行排序,并从 header 和第一列中删除重复数据。为了删除重复值,我使用了以下代码:

-(void) requestFinished: (ASIHTTPRequest *) request
{
    NSString *theJSON = [request responseString];

    SBJsonParser *parser = [[SBJsonParser alloc] init];

    NSMutableArray *jsonDictionary = [parser objectWithString:theJSON error:nil];

    headData = [[NSMutableArray alloc] init];
    NSMutableArray *head = [[NSMutableArray alloc] init];

    leftTableData = [[NSMutableArray alloc] init];
    NSMutableArray *left = [[NSMutableArray alloc] init];

    rightTableData = [[NSMutableArray alloc]init];

    for (NSMutableArray *dictionary in jsonDictionary)
    {
        Model *model = [[Model alloc]init];

        model.cid = [[dictionary valueForKey:@"cid"]intValue];
        model.iid = [[dictionary valueForKey:@"iid"]intValue];
        model.yr = [[dictionary valueForKey:@"yr"]intValue];
        model.val = [dictionary valueForKey:@"val"];

        [mainTableData addObject:model];

        [head addObject:[NSString stringWithFormat:@"%ld", model.yr]];
        [left addObject:[NSString stringWithFormat:@"%ld", model.iid]];
    }
    NSOrderedSet *orderedSet = [NSOrderedSet orderedSetWithArray:head];
    headData = [[orderedSet array] mutableCopy];

//    NSSet *set = [NSSet setWithArray:left];
//    NSArray *array2 = [set allObjects];
//    NSLog(@"%@", array2);

    NSOrderedSet *orderedSet1 = [NSOrderedSet orderedSetWithArray:left];
    NSMutableArray *arrLeft = [[orderedSet1 array] mutableCopy];

    //remove duplicate enteries from header array
    [leftTableData addObject:arrLeft];


    NSMutableArray *right = [[NSMutableArray alloc]init];
    for (int i = 0; i < arrLeft.count; i++)
    {
        NSMutableArray *array = [[NSMutableArray alloc] init];
        for (int j = 0; j < headData.count; j++)
        {
            /* NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.iid == %ld", [[arrLeft objectAtIndex:i] intValue]];
             NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];*/
            NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.iid == %ld AND SELF.yr == %ld", [[arrLeft objectAtIndex:i] intValue], [[headData objectAtIndex:j] intValue]];
            NSArray *filteredArray = [mainTableData filteredArrayUsingPredicate:predicate];

            if([filteredArray count]>0)
            {
                Model *model = [filteredArray objectAtIndex:0];
                [array addObject:model.val];
            }
        }
        [right addObject:array];
    }
    [rightTableData addObject:right];
}

如何对数组进行升序排序?

请帮忙。

NSSet 仅将非重复对象保留在其内部,以便仅将唯一对象保留在数组中,您可以使用 NSSet as -

假设您有包含重复对象的数组

NSArray *arrayA = @[@"a", @"b", @"a", @"c", @"a"];
NSLog(@"arrayA is: %@", arrayA);

//create a set with the objects from above array as
//the set will not contain the duplicate objects from above array
NSSet *set = [NSSet setWithArray: arrayA];

// create another array from the objects of the set
NSArray *arrayB = [set allObjects];
NSLog(@"arrayB is: %@", set);

上面的输出看起来像:

arrayA is: (
    a,
    b,
    a,
    c,
    a
)
arrayB is: {(
    b,
    c,
    a
)}

要按升序对可变数组进行排序,您可以使用 NSSortDescriptorsortUsingDescriptors:sortDescriptors。您还需要提供将根据哪个数组进行排序的键。

NSSortDescriptor *sortDescriptor;
sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"key" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
[array sortUsingDescriptors:sortDescriptors];
[sortDescriptor release];

这里有你想要的

//sort description will used to sort array.
NSSortDescriptor *descriptor=[[NSSortDescriptor alloc] initWithKey:@"iid" ascending:YES];
NSArray *descriptors=[NSArray arrayWithObject: descriptor];
NSArray *reverseOrder=[arrLeft sortedArrayUsingDescriptors:descriptors];

reverseOrder是你想要的输出。

还有另一种方法可以对遵循模型的对象进行排序。

NSArray *someArray = /* however you get an array */    
NSArray *sortedArray = [someArray sortedArrayUsingComparator:^(id obj1, id obj2) {
 NSNumber *rank1 = [obj1 valueForKeyPath:@"iid"];
NSNumber *rank2 = [obj2 valueForKeyPath:@"iid"];
return (NSComparisonResult)[rank1 compare:rank2];
}];

这里 sortedArray 是我们的输出。

您也可以为 yr 键替换相同的东西。

好的,所以你有一个看起来像这样的模型对象...

@interface Model: NSObject

@property NSNumber *idNumber;
@property NSNumber *year;
@property NSString *value;

@end

请注意,我有意使用 NSNumber 而不是 NSInteger,原因会变得很清楚。

目前您正试图在一个地方做很多事情。不要这样做。

创建一个新对象来存储此数据。然后您可以添加方法来获取您需要的数据。看到您在按年份划分的 table 视图中显示,然后每个部分按 idNumber 排序,那么我会做这样的事情...

@interface ObjectStore: NSObject

- (void)addModelObject:(Model *)model;

// standard table information
- (NSInteger)numberOfYears;
- (NSInteger)numberOfIdsForSection:(NSinteger)section;

// convenience methods
- (NSNumber *)yearForSection:(NSInteger)section;
- (NSNumber *)idNumberForSection:(NSInteger)section row:(NSInteger)row;
- (NSArray *)modelsForSection:(NSInteger)section row:(NSInteger)row;

// now you need a way to add objects
- (void)addModelObject:(Model *)model;

@end

现在开始实施。

我们要将所有内容存储在一本字典中。键将是 years,对象将是字典。在这些字典中,键将是 idNumbers,对象将是数组。这些数组将保存模型。

像这样...

{
    2010 : {
        1 : [a, b, c],
        3 : [c, d, e]
    },
    2013 : {
        1 : [g, h, u],
        2 : [e, j, s]
    }
}

我们还将使用所有便捷方法来执行此操作。

@interface ObjectStore: NSObject

@property NSMutableDictionary *objectDictionary;

@end

@implementation ObjectStore

 + (instancetype)init
{
    self = [super init];

    if (self) {
        self.objectDictionary = [NSMutableDictionary dictionary];
    }

    return self;
}

 + (NSInteger)numberOfYears
{
    return self.objectDictionary.count;
}

 + (NSInteger)numberOfIdsForSection:(NSinteger)section
{
    // we need to get the year for this section in order of the years.
    // lets create a method to do that for us.
    NSNumber *year = [self yearForSection:section];

    NSDictionary *idsForYear = self.objectDictionary[year];

    return idsForYear.count;
}

- (NSNumber *)yearForSection:(NSInteger)section
{
    // get all the years and sort them in order
    NSArray *years = [[self.obejctDictionary allKeys] sortedArrayUsingSelector:@selector(compare:)];

    // return the correct year
    return years[section];
}

- (NSNumber *)idNumberForSection:(NSInteger)section row:(NSInteger)row
{
    // same as the year function but for id
    NSNumber *year = [self yearForSection:section];

    NSArray *idNumbers = [[self.objectDictionary allKeys]sortedArrayUsingSelector:@selector(compare:)];

    return idNumbers[row];
}

- (NSArray *)modelsForSection:(NSInteger)section row:(NSInteger)row
{
    NSNumber *year = [self yearForSection:section];
    NSNumber *idNumber = [self idForSection:section row:row];

    return self.objectDictionary[year][idNumber];
}

// now we need a way to add objects that will put them into the correct place.

- (void)addModelObject:(Model *)model
{
    NSNumber *modelYear = model.year;
    NSNumber *modelId = model.idNumber;

    // get the correct storage location out of the object dictionary
    NSMutableDictionary *idDictionary = [self.objectDictionary[modelYear] mutableCopy];

    // there is a better way to do this but can't think atm
    if (!idDictionary) {
        idDictionary = [NSMutableDictionary dictionary];
    }

    NSMutableArray *modelArray = [idDictionary[modelId] mutableCopy];

    if (!modelArray) {
        modelArray = [NSMutableArray array];
    }

    // insert the model in the correct place.
    [modelArray addObject:model];
    idDictionary[modelId] = modelArray;
    self.objectDictionary[modelYear] = idDictionary;
}

@end

完成所有这些设置后,您现在可以用这个替换您的复杂函数...

-(void) requestFinished: (ASIHTTPRequest *) request
{
    NSString *theJSON = [request responseString];
    SBJsonParser *parser = [[SBJsonParser alloc] init];
    NSDictionary *jsonDictionary = [parser objectWithString:theJSON error:nil];

    for (NSDictionary *dictionary in jsonDictionary)
    {
        Model *model = [[Model alloc]init];

        model.cid = [dictionary valueForKey:@"cid"];
        model.idNumber = [dictionary valueForKey:@"iid"];
        model.year = [dictionary valueForKey:@"yr"];
        model.val = [dictionary valueForKey:@"val"];

        [self.objectStore addModelObject:model];
    }
}

要获取特定行的模型,只需使用...

[self.objectStore modelsForSection:indexPath.section row:indexPath.row];

要在 table视图委托方法中获取节数...

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.objectStore numberOfYears];
}

不要乱用视图控制器中的模型。

欢迎使用 MVC 模式。

此处有大量代码,但通过将所有代码放在此处,您可以从 VC.

中删除所有复杂代码

这就是我按升序对 header 数据进行排序并从 header 和最左边的列中删除重复项的方法。希望这会对其他人有所帮助

NSOrderedSet *orderedSet3 = [NSOrderedSet orderedSetWithArray:head3];
headData3 = [[orderedSet3 array] mutableCopy];
[headData3 sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2)
{
    return [str1 compare:str2 options:(NSNumericSearch)];
}];

NSOrderedSet *orderedSet4 = [NSOrderedSet orderedSetWithArray:left3];
NSMutableArray *arrLeft3 = [[orderedSet4 array] mutableCopy];

[leftTableData3 addObject:arrLeft3];