/**
* 數(shù)組遍歷的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];
// 添加數(shù)據(jù)
[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學習之集合遍歷
最后編輯于 :
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
相關閱讀更多精彩內容
- 一、使用for循環(huán) 要遍歷字典、數(shù)組或者是集合,for循環(huán)是最簡單也用的比較多的方法,示例如下: 優(yōu)點:簡單 缺點...
- 一 、遍歷 For 循環(huán)遍歷 NSEnumerator 枚舉器遍歷 數(shù)組,字典,集合都有一個枚舉器方法,返回的是枚...
- A ------ >遍歷概念 1、集合 ( collection ) OC 中提供的容器 : 數(shù)組,字典,集合 2...
- 明天就是七夕節(jié)了,祝各位女生七夕節(jié)快樂! 為什么單祝女生呢?因為我覺得,女生,不管是單身還是有伴侶,都要獨立...