OC学习之集合遍历

2016-03-24  本文已影响66人  龙马君
/**
 *  数组遍历的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];
    
    // 添加数据
    [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);
    }
    
}


上一篇下一篇

猜你喜欢

热点阅读