Search code examples
objective-cjsonnsarray

Remove Object in NSArray (Objective-C)


I have an NSArray (moodArray) that contains all my json, and I have another NSArray (idArray) that contains id and if idArray the id are present in moodArray should be deleted objects in the moodArray ? How to do ? Thank you

My code :

- (void)fetchEntries
    {
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        [manager GET:API_V3_CHANNEL_URL parameters:nil progress:nil success:^(NSURLSessionTask *task, id responseObject) {

            NSDictionary *searchDict = responseObject;

            // On filtre le json
            NSPredicate *firstNamePredicate = [NSPredicate predicateWithFormat:@"status == %@", @"LIVE"];
            NSPredicate *lastNamePredicate = [NSPredicate predicateWithFormat:@"status == %@", @"PAUSE"];

            NSPredicate *compoundPredicate = [NSCompoundPredicate orPredicateWithSubpredicates:@[firstNamePredicate, lastNamePredicate]];

// My idArray
            NSArray *idArray = [[NSArray alloc] initWithObjects:@"56ead10ae3c9a053398b4580", @"56efq10ae3c9a053398b4590", nil];

// My moodArray (content alljson)     
            self.moodArray = [[searchDict objectForKey:@"CONTESTS"] filteredArrayUsingPredicate:compoundPredicate];



            [self.collectionView reloadData];
        } failure:^(NSURLSessionTask *operation, NSError *error) {
            NSLog(@"Error: %@", error);
        }];

    }

My moodArray (json) : My json

I would check if moodArray contains the same id that idArray and if so delete the objects that have the same id in moodArray


Solution

  • Are the JSON objects strings? If so, I would use NSJSONSerialization to convert them into a dictionary and then extract the ID.

    -(NSDictionary*) convertJSONStringToDictionary:(NSString*)jsonString
    {
        NSError         *error;
        NSData          *objectData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary    *dictionary = [NSJSONSerialization JSONObjectWithData:objectData
                                                         options:NSJSONReadingMutableContainers
                                                           error:&error];
        return dictionary;
    

    }

    you could clean the array with something like:

    -(NSArray*)removeIDs:(NSArray*)idArray fromArray:(NSArray*)moodArray
    {
        NSMutableArray          *cleanedMoodArray = [NSMutableArray array];
    
        for (NSString *jsonString in moodArray) {
            NSDictionary    *moodDictionary = [self convertJSONStringToDictionary:jsonString];
            NSString        *objectID = [moodDictionary objectForKey:@"id"];
    
            if (nil != objectID) {
                    if (![idArray containsObject:objectID])
                        [cleanedMoodArray addObject:moodDictionary];
            }
    
        }
    
        return cleanedMoodArray;
    }