菜鸟教程小白 发表于 2022-12-13 09:57:32

ios - 通过索引和元素枚举 NSArray 的惯用方法


                                            <p><p>我需要在 <code>iOS</code> 中使用 <code>NSArray</code> 执行类似于 python 的 <code>enumerate()</code> 函数的操作(我还必须构建 NSIndexPath 对象检查对象)。</p>

<p>我没有看到用于执行此类操作的内置方法(即没有 NSArray 等效于 NSDictionary 的 enumerateKeysAndObjectsUsingBlock: 方法)。这让我想到了两种通用的方法。</p>

<pre><code>for (NSUInteger index = 0; index &lt; mySequence.count; index++) {
    MyElementType *element = mySequence;
    //
    // code that works with both index and element
    //
}
</code></pre>

<p>或</p>

<pre><code>NSUInteger index = 0;
for (MyElementType *element in mySequence) {
    //
    // code that works with both index and element
    //
    index++;
}
</code></pre>

<p>是否有充分的理由选择其他?或者有没有比这两种方法更好的第三种方法?</p></p>
                                    <br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
                                            <p><p>NSArray 中有以下 API:</p>

<pre><code>- (void)enumerateObjectsUsingBlock:(void (^)(id obj, NSUInteger idx, BOOL *stop))
</code></pre></p>
                                   
                                                <p style="font-size: 20px;">关于ios - 通过索引和元素枚举 NSArray 的惯用方法,我们在Stack Overflow上找到一个类似的问题:
                                                        <a href="https://stackoverflow.com/questions/27139156/" rel="noreferrer noopener nofollow" style="color: red;">
                                                                https://stackoverflow.com/questions/27139156/
                                                        </a>
                                                </p>
                                       
页: [1]
查看完整版本: ios - 通过索引和元素枚举 NSArray 的惯用方法