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

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)

  • 确实,在这种情况下,块仅用于此范围.但是,通常,可以从函数中复制和返回块,并在以后这些变量不再存在时使用.在这种情况下,此解决方案将无法工作,并将覆盖任意内存 (8认同)
  • 你不必发布任何东西.指针`pointsPtr`是一个普通变量,它的值是(在pointsPtr = points`之后)数组的第一个元素`points`的内存地址.所以当你声明`points [10]`时,编译器会在堆栈中为10`CGPoint`保留内存,然后`pointsPtr`只指向这个内存.由于你没有为`malloc` /`calloc`在堆上为`pointsPtr`分配任何内存,所以没有什么可以释放的.这就是我喜欢这种方法的原因.顺便说一句,我本可以用`CGPoints points [10]开始我的代码; CGPoint*pointsPtr = points;`这是完全一样的. (2认同)

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)