NSArray *myArray = [NSArray arrayWithObjects:@"1",@"2",@"3",@"4",nil];//初始多个元素的数组
//或者NSArray *myArray = @[@"1",@"2",@"3",@"4"];
//快速枚举
for(id/*NSString*/ obj in myArray)
{
NSLog(@"%@",obj);
}
它跟平时我们用的效果是一样的
for(NSUInteger number = 0 ; number<myArray.count/*数组长度*/ ; number++)
{
NSString* str = [myArray objectAtIndex:number];
NSLog(@"%@", str);
//或者NSLog(@"%@",myArray[number]);
}
//通过实验得出结论:枚举过程中数组不能改变,否则会抛出异常,下面提供了一个遍历时想要改变数组的办法
1 NSMutableArray *arr1 = [NSMutableArray arrayWithObjects:@"123",@"456",@"789",nil];
2 NSMutableArray *arr2 = [NSMutableArray arrayWithArray:arr1];//将arr1复制给arr2
3 //遍历arr2,处理arr1
4 int i=0;
5 for( id num in arr2)
6 {
7 if([num isEqualToString:@"456"])
8 arr1[i] = @"555";
9 i++;
10 }
11 NSLog(@"%@",arr1);
结果将@“456”替换为@“555”;