Доступ к массиву C внутри блоков (переменная array count) Objective-C


Блоки хороши, но как насчет написания массивов C?

Учитывая эту упрощенную ситуацию:

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

После некоторого поиска нашел это возможное решение, чтобы поместить его в структуру:

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

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

Это будет работать, но есть небольшое ограничение, которое я должен создать массив c динамически:

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;

Как я могу получить доступ к моему массиву CGPoint в пределах block?

Или

Возможно ли это вообще или мне нужно переписать метод block, Чтобы получить полный функциональность?

2 17

2 ответа:

Может быть, вы можете выделить массив в куче?

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

Еще один простой ответ, который работает для меня, следующий:

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