How for in loop works internally - Objective C - Foundation

后端 未结 1 438
谎友^
谎友^ 2021-01-06 00:46

I found this answer:

https://stackoverflow.com/a/5163334/1364174

Which presents how for in loop is implemented.

NSFastEnumeratio         


        
相关标签:
1条回答
  • 2021-01-06 01:19

    First of all, strong pointers cannot be used in C-structures, as explained in the "Transitioning to ARC Release Notes", therefore the objects array has be be declared as

    __unsafe_unretained  id __objects[MAX_STACKBUFF_SIZE];
    

    if you compile with ARC.

    Now it is not obvious (to me) from the NSFastEnumeration documentation, but it is explained in Cocoa With Love:Implementing countByEnumeratingWithState:objects:count: that the implementation need not fill the supplied objects array, but can just set __enumState.itemsPtr to an existing array (e.g. some internal storage). In that case, the contents of the __objects array is undefined, which causes the crash.

    Replacing

    id obj = __objects[i];
    

    by

    id obj = __enumState.itemsPtr[i];
    

    gives the expected result, which is what you observed.

    Another reference can be found in the "FastEnumerationSample" sample code:

    You have two choices when implementing this method:

    1) Use the stack based array provided by stackbuf. If you do this, then you must respect the value of 'len'.

    2) Return your own array of objects. If you do this, return the full length of the array returned until you run out of objects, then return 0. For example, a linked-array implementation may return each array in order until you iterate through all arrays.

    In either case, state->itemsPtr MUST be a valid array (non-nil). ...

    0 讨论(0)
提交回复
热议问题