Passing and calling dynamic blocks in Objective-C

As part of the unit test structure, I am writing a function genArraythat will generate an NSArrays populated with the one passed in the generator block. This way it [ObjCheck genArray: genInt]will generate an NSArray of random integers, it [ObjCheck genArray: genChar]will generate an NSArray of random characters, etc. In particular, I get compiler errors in my implementation genArrayand genString, wrapper around [ObjCheck genArray: genChar].

I believe that Objective-C can manage blocks dynamically, but I don't have the correct syntax.

ObjCheck.m

+ (id) genArray: (id) gen {
    NSArray* arr = [NSMutableArray array];

    int len = [self genInt] % 100;

    int i;
    for (i = 0; i < len; i++) {
        id value = gen();

        arr = [arr arrayByAddingObject: value];
    }

    return arr;
}

+ (id) genString {
    NSString* s = @"";

    char (^g)() = ^() {
        return [ObjCheck genChar];
    };

    NSArray* arr = [self genArray: g];
    s = [arr componentsJoinedByString: @""];

    return s;
}

, gcc , gen(), gen . , gen , id, .

id^() id, . Objective C (genArray ), ?

+5
3

, , id , , , ( , "" *).

BTW, id^() . id(^)(). . +genArray:,

id value = ((id(^)())(gen))();

, .

* , llvm obj-c, , , .

+7

- C, ObjC - . . ( .)

gen a id (^gen)(). (, , a void*, id , gen ObjC, .)

+1

, , . , , , .

NSArray. . Objective C. - , componentsJoinedByString, NSStrings g. genArray , id ^(). , . - :

+ (id) genArray: (id^()) gen;

+ (id) genString {
    ...
    NSString * (^g)() = ^() {
        return [NSString stringWithFormat:@"%c", [ObjCheck genChar]];
    };
    ...
}

NSString * - . char . NSString * ^() id ^(), char ^() id ^(). genArray char ^(), genArray, genArray, arrayByAddingObject, .

Someone who understands the subtleties of block syntax can edit my post if I get some subtle syntax errors.

Btw, use NSMutableArray as a local variable in genArray. Presenting, arrayByAddingObject is called again and again, will have O (n ^ 2) performance. You can still declare the return type as NSArray, which is the superclass of NSMutableArray, and the calling genArray elements will not know the difference.

+1
source

All Articles