OC學習之集合遍歷

/**
 *  數(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里面放的是對象,基本類型被轉為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(@"字典遍歷對象:value: %@", value);
    }
    
}


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

相關閱讀更多精彩內容

友情鏈接更多精彩內容