Access C Array within blocks (variable array count) Objective-C

后端 未结 2 797
走了就别回头了
走了就别回头了 2020-12-16 12:58

Blocks are fine but what about writing C arrays?

Given this simplified situation:

CGPoint points[10];
[myArray forEachElementWithBlock:^(int idx) {
          


        
相关标签:
2条回答
  • 2020-12-16 13:14

    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;
    
    0 讨论(0)
  • 2020-12-16 13:21

    Another simple answer which works for me is the following:

    CGPoint points[10], *pointsPtr;
    pointsPtr = points;
    [myArray forEachElementWithBlock:^(int idx) {
        pointsPtr[idx] = CGPointMake(10, 20);
    }];
    
    0 讨论(0)
提交回复
热议问题