Подтвердить что ты не робот

Доступ к массиву C внутри блоков (количество переменных массивов) 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?

ИЛИ

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

4b9b3361

Ответ 1

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

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

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

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