NSArray *array = [NSArray arrayWithObjects: @“1”,@“2”,@“3”,nil];
//array[i] = [array objectAtIndex:i]
一. for循环
int count = array.count;//减少调用次数
for( int i=0; i<count; i++){
NSLog(@"%i-%@", i, array[i]);
}
二. 增强for
for(id obj in array){
NSLog(@"%@",elm);
}
三. 迭代器
NSEnumerator *enumerator = [array objectEnumerator];
NSArray *obj = nil;
while(obj = [enumerator nextObject]){
NSLog(@"obj=%@",obj);
}
四. Block块遍历
[array enumeratorObjectsUsingBlock:
^(NSArray *obj, NSUInteger idx, BOOL *stop){
NSLog(@"%i-%@",idx,elm);
//若终断循环
//*stop = YES;
}];
比如:
内容只是重要的代码块,需要实现请将各代码块放在main函数中去运行
NSArray *arr = @[@1,@2,@3,@4,@6];
NSMutableArray *array = [NSMutableArray arrayWithArray:arr];
NSNumber *value = @5;
//现在要将@5插入,使array内部排序为@1,@2,@3,@4,@5,@6
用四种方法实现和输出
第一种:
for(int i = 0; i<array.count;i++)
{
int elm = [array[i] intValue];
int val = [value intValue];
if (val < elm) {
[array insertObject:value atIndex:i];
break;
}
}
for(int i = 0;i<array.count;i++)
{
NSLog(@"%@",array[i]);
}
第二种:
for (id obj in array) {
unsigned long i = [array indexOfObject:obj];
if([value intValue]<[array[i] intValue])
{
[array insertObject:value atIndex:i];
break;
}
}
for (id obj in array) {
NSLog(@"%@",obj);
}
第三种:
NSEnumerator *enumerator = [array objectEnumerator];
id obj = nil;
while (obj = [enumerator nextObject]) {
unsigned long i = [array indexOfObject:obj];
if([value intValue]<[array[i] intValue])
{
[array insertObject:value atIndex:i];
break;
}
}
NSEnumerator *enumerator1 = [array objectEnumerator];
obj = nil;
while (obj = [enumerator1 nextObject]) {
NSLog(@"%@",obj);
}
第四种:
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx,BOOL *stop) {
if([value intValue]<[array[idx] intValue])
{
[array insertObject:value atIndex:idx];
*stop = YES;
}
}];
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSLog(@"%lu - %@",idx,obj);
}];