块是可以的,但怎么写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
方法才能获得所有功能?
pointsPtr
是一个普通变量,其值是(在pointsPtr = points
之后)数组points
的第一个元素的内存地址。因此,当您声明points[10]
时,编译器会在堆栈上为10个CGPoint
保留内存,然后pointsPtr
只是指向这个内存。由于您没有使用malloc
/calloc
在堆上分配任何内存给pointsPtr
,因此无需释放任何内容。这就是我喜欢这种方法的原因。顺便说一下,我也可以用CGPoints points[10]; CGPoint *pointsPtr = points;
开始我的代码,这完全相同。 - cefstat