代码块很好,但是如何编写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;
如何在block
中访问我的CGPoint
数组?
或
这有可能吗?或者我必须重写block方法才能获得完整的功能吗?
发布于 2011-03-28 15:14:18
也许你可以在堆上分配数组?
// 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;
发布于 2011-06-22 18:19:55
另一个对我有效的简单答案是:
CGPoint points[10], *pointsPtr;
pointsPtr = points;
[myArray forEachElementWithBlock:^(int idx) {
pointsPtr[idx] = CGPointMake(10, 20);
}];
https://stackoverflow.com/questions/5455592
复制相似问题