Koichi Adachi

smart phone app development tips

block構文で再帰処理を書いてみる(NSNullを削除)

いまのところの最新はこれ。 もうちょっとすっきり書きたいなぁ

    id (^func)(id);
    __block __weak id (^weak_func)(id) = func = (id) ^(id collection){
        __block id mutableDic = [@{} mutableCopy];
        [collection enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if(obj == [NSNull null]){
                return;
            }
            [mutableDic setObject:[obj isKindOfClass:[NSDictionary class]] ? weak_func(obj) : obj
                           forKey:key];
        }];
        return [NSDictionary dictionaryWithDictionary:mutableDic];
    };

実行してみる

    NSDictionary *source = @{@"k1": @"v1"
                             ,@"k2": @"v2"
                             ,@"k3": [NSNull null]
                             ,@"k4": @{@"k4-1": @"v1"
                                       ,@"k4-2": @"v2"
                                       ,@"k4-3": [NSNull null]
                                       ,@"k4-4": @"v4"
                                       }
                             };
    NSLog(@"加工前 %@", [source description]);
    id changdSource = func(source);
    NSLog(@"加工後 %@", [changdSource description]);

初期状態。アドバイスをもらって↑になった。

    __block __weak id (^weak_func)(id);
    id (^func)(id);
    weak_func = func = (id) ^(id dic){
        __block NSMutableDictionary *mutableDic = [dic mutableCopy];
        [mutableDic enumerateKeysAndObjectsUsingBlock:^(id key, id obj, BOOL *stop) {
            if(obj == [NSNull null]){
                [mutableDic removeObjectForKey:key];
            }else if([obj isKindOfClass:[NSDictionary class]]){
                obj = weak_func(obj);
                [mutableDic setObject:obj forKey:key];
            }
        }];
        return mutableDic;
    };

詳解 Objective-C 2.0 第3版

詳解 Objective-C 2.0 第3版