Objective-C中,遍历数组的四种方法

本文详细介绍了Objective-C中四种遍历数组的方法,并提供了示例代码,包括通过索引遍历、使用NSEnumerator、快速枚举和代码块方法。帮助开发者更高效地操作数组。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在Objective-C中,博主总结了四种方法来遍历数组,以下是分享,希望有用。

#import <Foundation/Foundation.h>

@interface Tire : NSObject

@end
@implementation Tire

-(NSString *)description
{
    return @"I am a Tire";
}

@end

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...

        NSMutableArray *array = [NSMutableArray arrayWithCapacity:40];
        for(NSInteger i = 0;i < 4;i++)
        {
            Tire *tire = [Tire new];//创建类对象tire
            [array addObject:tire];//为可变数组array添加元素
        }
        //1、通过索引遍历数组
        for(NSInteger i = 0;i < [array count];i++)
        {
            NSLog(@"index %lu has %@",(long)i,[array objectAtIndex:i]);//结合计数和取值功能来输出数组内容(使用方法:-(id)objectAtIndex:(NSUInteger)index)
        }
        [array removeObjectAtIndex:1];//删除数组中索引为1的元素
        for(NSInteger i = 0;i < [array count];i++)
        {
            NSLog(@"index %lu has %@",(long)i,array[i]);//使用数组字面量语法来获取数组元素
        }
        //2、使用NSEnumerator遍历数组
        NSEnumerator *enumerator = [array objectEnumerator];
        id thingie;
        while(thingie = [enumerator nextObject])
        {
            NSLog(@"I found %@",thingie);
        }
        //3、使用快速枚举遍历数组
        NSString *object;
        for(object in array)
        {
            NSLog(@"%@",object);
        }
        //4、通过代码块方法遍历数组(-(void)enumerateObjectsUsingBlock:(void(^)(id obj,NSUInteger idx,BOOL *stop))block)
        [array enumerateObjectsUsingBlock:^(NSString *string,NSUInteger index,BOOL *stop){
            NSLog(@"You found %@",string);
        }];

    }
    return 0;
}

以上就是博主的分享,有所补充希望读者也能提出,谢谢了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值