删除NSArray中的对象(Objective-C)

时间:2016-04-02 08:50:59

标签: objective-c json nsarray

我有一个包含我所有json的NSArray(moodArray),并且我有另一个包含id的NSArray(idArray),如果idArray在moodArray中存在id,应该在moodArray中删除对象?怎么做 ?谢谢

我的代码:

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

    }

我的心情阵容(json): My json

我会检查moodArray是否包含与idArray相同的id,如果是,则删除moodArray中具有相同id的对象

1 个答案:

答案 0 :(得分:0)

JSON对象是字符串吗?如果是这样,我会使用NSJSONSerialization将它们转换为字典,然后提取ID。

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

}

您可以使用以下内容清理数组:

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