在块内访问C数组(可变数组计数)Objective-C

时间:2011-03-28 06:55:32

标签: objective-c struct core-graphics objective-c-blocks arrays

块很好但是编写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数组?

OR

它甚至可能还是我必须重写块方法才能获得完整的功能?

2 个答案:

答案 0 :(得分:18)

另一个对我有用的简单答案如下:

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

答案 1 :(得分:14)

也许你可以在堆上分配数组?

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