18 arrays struct core-graphics objective-c objective-c-blocks
块很好但是编写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
}];
Run Code Online (Sandbox Code Playgroud)
在搜索了一段时间后找到了这个可能的解决方案,把它放在一个结构中:
__block struct {
CGPoint points[100];
} pointStruct;
[myArray forEachElementWithBlock:^(int idx) {
pointStruct.points[idx] = CGPointMake(10, 20);
}];
Run Code Online (Sandbox Code Playgroud)
这会起作用,但我有一点限制,我必须动态创建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;
Run Code Online (Sandbox Code Playgroud)
如何CGPoint在一个内部访问我的阵列block?
要么
它甚至是可能的还是我必须重写块方法才能获得完整的功能?
cef*_*tat 18
另一个对我有用的简单答案如下:
CGPoint points[10], *pointsPtr;
pointsPtr = points;
[myArray forEachElementWithBlock:^(int idx) {
pointsPtr[idx] = CGPointMake(10, 20);
}];
Run Code Online (Sandbox Code Playgroud)
zou*_*oul 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;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7601 次 |
| 最近记录: |