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

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

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); // 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?

回答1:

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;


回答2:

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); }];


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!