一段可以清理NSArray中的空对象的代码(递归)

- (NSArray *)clearAllNullObject{
    NSMutableArray *array = [self mutableCopy];
    for (int i = 0;i < array.count;i++) {
        id obj = array[i];
        if ([obj isKindOfClass:[NSDictionary class]]){
            NSMutableDictionary *dict = [obj mutableCopy];
            for (int j = 0; j<dict.allKeys.count; j++) {
                id tObj = dict[dict.allKeys[j]];
                if ([tObj isKindOfClass:[NSNull class]]){
                    [dict removeObjectForKey:dict.allKeys[j]];
                    j--;
                }
                if ([tObj isKindOfClass:[NSArray class]]){
                    NSArray *to = [tObj clearAllNullObject];
                    [dict setObject:to forKey:dict.allKeys[j]];

                }
            }
            [array replaceObjectAtIndex:i withObject:dict];
        }
        if ([obj isKindOfClass:[NSArray class]]){
            [array replaceObjectAtIndex:i withObject:[obj clearAllNullObject]];
        }
    }
    return array;
}

使用方法:

创建NSArray的category

        NSArray *obj = [data clearAllNullObject];

 

posted @ 2016-11-08 18:00  老徐想减肥  阅读(831)  评论(0编辑  收藏  举报