块中访问C中的数组(可变数组数)的Objective-C [英] Access C Array within blocks (variable array count) Objective-C
本文介绍了块中访问C中的数组(可变数组数)的Objective-C的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
块是罚款,但有关编写C数组是什么?
Blocks are fine but what about writing C arrays?
鉴于这种情况的简化:
CGPoint points[10];
[myArray forEachElementWithBlock:^(int idx) {
points[idx] = CGPointMake(10, 20); // error here
// Cannot refer to declaration with an array type inside block
}];
在寻找了一段时间发现了这个可能的解决方案,把它在一个结构:
after searching a while found this possible solution, to put it in a struct:
__block struct {
CGPoint points[100];
} pointStruct;
[myArray forEachElementWithBlock:^(int idx) {
pointStruct.points[idx] = CGPointMake(10, 20);
}];
这会工作,但有一点限制我必须动态创建C数组:
this would work but there is a little limitation I have to create the c array dynamically:
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
阵列
How can I access my CGPoint
array within a block
?
或
它甚至有可能在全部或我重写块方法来获得完整的功能?
Is it even possible at all or do I have to rewrite the block method to get the full functionality?
推荐答案
也许你可以在堆中分配的数组?
Maybe you can allocate the array on the heap?
// 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;
这篇关于块中访问C中的数组(可变数组数)的Objective-C的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文