开发者

Access C Array within blocks (variable array count) Objective-C

Blocks are fine but what about writing C arrays?

Given this simplified situation:

CGPoint points[10];
[myArray forEachElementWithBlock:^(int idx) {
    points[idx] = CGPointMake(10, 20); //开发者_Python百科 error here
    // Cannot refer to declaration with an array type inside block
}];

after searching a while found this possible solution, to put it in a struct:

__block struct {
    CGPoint points[100];
} pointStruct;

[myArray forEachElementWithBlock:^(int idx) {
    pointStruct.points[idx] = CGPointMake(10, 20);
}];

this would work but there is a little limitation I have to create the c array dynamically:

int count = [str countOccurencesOfString:@";"];
__block struct {
    CGPoint points[count]; // error here
    // Fields must have a constant size: 'variable length array in structure' extension will never be supported
} pointStruct;

How can I access my CGPoint array within a block?

OR

Is it even possible at all or do I have to rewrite the block method to get the full functionality?


Another simple answer which works for me is the following:

CGPoint points[10], *pointsPtr;
pointsPtr = points;
[myArray forEachElementWithBlock:^(int idx) {
    pointsPtr[idx] = CGPointMake(10, 20);
}];


Maybe you can allocate the array on the heap?

// Allocates a plain C array on the heap. The array will have
// [myArray count] items, each sized to fit a CGPoint.
CGPoint *points = calloc([myArray count], sizeof(CGPoint));
// Make sure the allocation succeded, you might want to insert
// some more graceful error handling here.
NSParameterAssert(points != NULL);

// Loop over myArray, doing whatever you want
[myArray forEachElementWithBlock:^(int idx) {
    points[idx] = …;
}];

// Free the memory taken by the C array. Of course you might
// want to do something else with the array, otherwise this
// excercise does not make much sense :)
free(points), points = NULL;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜