objective-c數(shù)組的四種遍歷方法總結

pragma mark Array數(shù)組的四種遍歷方法

void testArray(){
Blog *blog1 = [[Blog blog] setBlogTitle:@"Love" andContent:@"I love you"];
Blog *blog2 = [[Blog blog] setBlogTitle:@"Friendship" andContent:@"you are my best friend"];
NSArray *array = [NSArray arrayWithObjects:@"hello",@"world",blog1,blog2, nil];

//第一種遍歷:普通for循環(huán)
long int count = [array count];
for (int i = 0 ; i < count; i++) {
    NSLog(@"1遍歷array: %zi-->%@",i,[array objectAtIndex:i]);
}

//第二種遍歷:快速for循環(huán),需要有外變量i
int i = 0;
for (id obj in array) {
    NSLog(@"2遍歷array:%zi-->%@",i,[array objectAtIndex:i]);
    i++;
}

//第三種遍歷:OC自帶方法enumerateObjectsUsingBlock:

//默認為正序遍歷
[array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSLog(@"3遍歷array:%zi-->%@",idx,obj);
}];
//NSEnumerationReverse參數(shù)為倒序遍歷
[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSLog(@"4倒序遍歷array:%zi-->%@",idx,obj);
}];

//第四種遍歷:利用枚舉
NSEnumerator *en = [array objectEnumerator];
id obj;
int j = 0 ;
while (obj = [en nextObject]) {
    NSLog(@"5遍歷array:%d-->%@",j,obj);
    j++;
}

}
int main(int argc, const char * argv[])
{
@autoreleasepool {
testArray();
}
return 0;
}

最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容