美文网首页
OC学习之集合遍历

OC学习之集合遍历

作者: 龙马君 | 来源:发表于2016-03-24 10:47 被阅读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);
        }
        
    }
    
    
    

    相关文章

      网友评论

          本文标题:OC学习之集合遍历

          本文链接:https://www.haomeiwen.com/subject/oarrlttx.html