iosobjective-cduplicatesgithub-mantle

Remove duplicates from NSMutableArray of NSDictionary depending on value of key


I have a NSMutableArray of, say, 10 NSMutableArrays. Each of these NSMutableArrays contains different number of NSDictionary objects for which I have made a model class. I get this data from an API response. First time you make an API call, the response will be the whole data. From then on, when API call is made, it returns only data that is modified.

When I get some new data from API response, it contains data that is already in the array of dictionaries but with slight modifications.

Model class's structure is as below:

SubCategory.h

@interface SubCategory : MTLModel <MTLJSONSerializing>

@property (nonatomic, retain) NSString *subCategoryID;
@property (nonatomic, retain) NSString *subCategoryName;
@property (nonatomic, retain) NSString *status;

@end

JSON object returned will look like this:

{
    "sub_category" =             (
                            {
                id = 55ed48123;
                name = "Sub Category 1";
                status = 1;
            },
                            {
                id = 55ed47ed3;
                name = "Sub Category 2";
                status = 1;
            }
      );
}

The 'id' field of new data is same. But its 'name' and 'status' fields are different. I want to replace the data in the NSMutableArray of NSDictionary objects with the new data so that it retains the order of the objects in this array. How can I do this?


Solution

  • 1: Use NSPredicate to create the criteria for the duplicate condition.

    2: Use filteredArrayUsingPredicate to get an array of duplicated objects.

    3: Remove one object from the duplicated array.

    4: Use removeObjectsInArray to remove the list of all objects in the duplicated array from the original array.