OC學(xué)習(xí)之集合遍歷

/**
 *  數(shù)組遍歷的4種方法:1.for;2.快速for;3.特性block;4.枚舉方法
 */
void testTraverse(){
    NSLog(@"-----------------testTraverse-------------");
    NSArray *array = [NSArray arrayWithObjects:@1,@2,@3,@4,@5, nil];
    // 第一種,for
    NSUInteger count = [array count];
    for (int i = 0; i < count; i++) {
        NSLog(@"1遍歷array:%zi-->%@", i, [array objectAtIndex: i]);
    }
    NSLog(@"-");
    
    // 第二種
    int i = 0;
    // array里面放的是對(duì)象,基本類型被轉(zhuǎn)為NSNumber
    for (NSNumber *value in array) {
         NSLog(@"2遍歷array:%zi-->%@", i, value);
        i++;
    }
    NSLog(@"-");
    
    // 第三種,OC自帶方法enumerateObjectsUsingBlock:
    [array enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop){
        NSLog(@"3遍歷array:%zi-->%@", idx, obj);
    }];
    
    [array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
        NSLog(@"3倒序遍歷array:%zi-->%@", idx, obj);
    }];
    NSLog(@"-");
    
    // 第四種,枚舉
    NSEnumerator *en = [array objectEnumerator];
    id obj;
    int j = 0;
    while (obj = [en nextObject]) {
        NSLog(@"4遍歷array:%zi-->%@", j, obj);
        j++;
    }
    
    NSLog(@"-字典遍歷-");
    // 字典遍歷
    NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithObjectsAndKeys:[[Person alloc] initWithName: @"xuzhiming" andAge:10], @0, nil];
    
    // 添加數(shù)據(jù)
    [dictionary setObject:[[Person alloc] initWithName:@"longma" andAge:30] forKey:@1];
    
    //快速枚舉遍歷所有KEY的值
    NSEnumerator *enKey = [dictionary keyEnumerator];
    id key;
    while (key = [enKey nextObject]) {
        //通過KEY找到value
        NSLog(@"字典遍歷:key: %@ value: %@", key, [dictionary objectForKey:key]);
    }
    
    //快速枚舉遍歷所有Value的值
    NSEnumerator *enValue = [dictionary objectEnumerator];
    id value;
    while (value = [enValue nextObject]) {
        NSLog(@"字典遍歷對(duì)象:value: %@", value);
    }
    
}


最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容