按升序对数组进行排序,并删除objective-c中的重复值

时间:2015-04-13 05:19:02

标签: ios objective-c json sorting nsmutablearray

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

-(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];
}

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

请帮忙。

4 个答案:

答案 0 :(得分:1)

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

@interface Model: NSObject

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

@end

注意,我故意使用NSNumber而不是NSInteger,原因很明显。

目前你想在一个地方做很多事情。不要这样做。

创建一个新对象来存储此数据。然后,您可以添加方法来获取所需的数据。看到你在按年份划分的表格视图中显示,然后按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];

获取tableview委托方法中的部分数...

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

在视图控制器中没有弄乱模型。

欢迎使用MVC模式。

这里有大量的代码,但是通过放置所有代码,您可以从VC中删除所有复杂的代码。

答案 1 :(得分:0)

NSSet只保留非重复的对象,以便只保留数组中的唯一对象,您可以使用NSSet作为 -

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

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];

答案 2 :(得分:0)

在这里,你会得到你想要的东西。

//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键替换相同的内容。

答案 3 :(得分:0)

这就是我按升序对标题数据进行排序以及从标题和最左列中删除重复项所做的操作。希望这会有助于其他人

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];