How for in loop works internally - Objective C - Foundation

流过昼夜 提交于 2019-11-30 20:58:05

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). ...

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!