objective-cuitableviewduplicatesnsarrayjsonmodel

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.

"<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.

As you can see, These have the same name and packageID but different version.

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.

This is how I set UITableView with data.

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

Solution

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