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

一段可以清理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

<style>p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 15.0px Menlo; color: #ffffff } span.s1 { } span.s2 { color: #00afca } span.s3 { color: #93c86a }</style>

        NSArray *obj = [data clearAllNullObject];

 

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