简体   繁体   English

如何从用JSONModel编写的NSArray中删除重复数据?

[英]How to remove duplicates data from NSArray written with JSONModel?

I use JSONModel to parse json and, convert it to NSArray to use it in UITableView . 我使用JSONModel解析json,然后将其转换为NSArray以在UITableView使用它。

"<RSTweakItem> \n   [name]: WhatAboutThis\n   [version]: 1.2\n   [packageID]: com.peterdev.whatabouthis\n</RSTweakItem>",
"<RSTweakItem> \n   [name]: WhatAboutThis\n   [version]: 1.2.1\n   [packageID]: com.peterdev.whatabouthis\n</RSTweakItem>"

this is the part of json data converted to NSArray with JSONModel . 这是JSON数据通过JSONModel转换为NSArrayJSONModel

As you can see, These have the same name and packageID but different version. 如您所见,它们具有相同的名称和packageID,但版本不同。

So I want to check the packageID to make sure it is the same package, then remove the old version of the data and leave only the latest version of the data. 因此,我想检查packageID以确保它是相同的软件包,然后删除数据的旧版本,并仅保留数据的最新版本。

This is how I set UITableView with data. 这就是我用数据设置UITableView

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    RSTweakCell *cell = [tableView dequeueReusableCellWithIdentifier:@"RSTweakCell" forIndexPath:indexPath];

    RSTweakItem *model = self.listTweak[indexPath.row];

    cell.textLabel.text = model.name;
    cell.detailTextLabel.text = model.version;
    cell.packageID = model.packageID;

    return cell;
}
NSArray<RSTweakItem> *models = @[];//parse from json
    NSMutableArray *packageIDs = [[models valueForKey:@"packageID"] mutableCopy];//get all packageIDs
    NSMutableArray *newModels= [NSMutableArray new];//for unique last versions of RSTweakItem
    while (packageIDs.count > 0) {
        NSString *pID = packageIDs.firstObject;
        //get all objects packageIDs equal pID
        NSArray *filteredAray = [models filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF.packageID like  %@", pID]];
        if(filteredAray.count  > 0) {
//            sort to get lates version
            NSArray *sorteArray = [filteredAray sortedArrayUsingComparator:^NSComparisonResult(RSTweakItem *obj1, RSTweakItem *obj2) {
                return [obj1.version compare:obj2.version];
            }];
            [newModels addObject:sorteArray.lastObject];
        }
        [packageIDs removeObject:pID];
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM