寫高質量OC程式碼52建議總結:48.多用塊列舉,少用for迴圈
阿新 • • 發佈:2019-01-30
以下是for迴圈針對NSArray,NSSet,NSDictionary的遍歷。字典和set都是無序的,無法根據特定的整數下標直接訪問其值。遍歷set和dictionary都需要而外建立陣列儲存物件和key。這個中介陣列增加了不必要的而外開支。
以下是通過NSEnumerator遍歷,nextObject方法可以返回列舉裡的下一個物件,等到所有資料都已經遍歷,該方法會返回nil。reverseObjectEnumerator返回陣列反向排列。--(void)demoforArray{ NSArray *anArray = /***/; for (int i = 0; i < anArray.count; i++) { id object = anArray[i]; // do something } } -(void)demoforSet{ NSSet *aSet = /***/; NSArray *objects = [aSet allObjects]; for (int i = 0; i < objects.count; i++) { id object = object[i]; // do something } } -(void)demoforDic{ NSDictionary *aDictionary = /***/; NSArray *keys = [aDictionary allKeys]; for (int i = 0; i < keys.count; i++) { id key = keys[i]; id value = aDictionary[key]; // do something } }
以下是快速遍歷方法-(void)demoNSEnumeratorForArray{ NSArray *anArray = /***/; NSEnumerator *enumerator = [anArray objectEnumerator]; id object; while ((object = [enumerator nextObject]) != nil) { // do something } } -(void)demoNSEnumeratorForSet{ NSSet *anSet = /***/; NSEnumerator *enumerator = [anSet objectEnumerator]; id object; while ((object = [enumerator nextObject]) != nil) { // do something } } -(void)demoNSEnumeratorForDic{ NSDictionary *anDic = /***/; NSEnumerator *enumerator = [anDic keyEnumerator]; id key; while ((key = [enumerator nextObject]) != nil) { // do something } }
以下是基於塊的便利方式-(void)demoFastForArray{ NSArray *anArray = /***/; for (id object in anArray) { // do something } } -(void)demoFastForSet{ NSSet *anSet = /***/; for (id object in anSet) { // do something } } -(void)demoFastForDic{ NSDictionary *anDic = /***/; for (id key in anDic) { id value = anDic[key]; // do something } }
-(void)enumerateObjectsUsingBlock:(void(^)(id object, NSUInteger idx, BOOL *stop))block;
前兩個引數,分別提供了所針對的物件和下標,第三個引數可以終止便利操作。
-(void)demoBlockForArray{
NSArray *anArray = /***/;
[anArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
// do something
if (....) {
*stop = YES;
}
}];
}
-(void)demoBlockForSet{
NSSet *aSet = /***/;
[aSet enumerateObjectsUsingBlock:^(id _Nonnull obj, BOOL * _Nonnull stop) {
// do something
if (...) {
*stop = YES;
}
}];
}
-(void)demoBlockForDic{
NSDictionary *dic = /***/;
[dic enumerateKeysAndObjectsUsingBlock:^(id _Nonnull key, id _Nonnull obj, BOOL * _Nonnull stop) {
// do something
if (shouldStop) {
*stop = YES;
}
}];
}
反向遍歷:NSEnumerationReverse,陣列和字典都對應兩個方法- (void)enumerateObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(ObjectType obj, NSUInteger idx, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
- (void)enumerateKeysAndObjectsWithOptions:(NSEnumerationOptions)opts usingBlock:(void (NS_NOESCAPE ^)(KeyType key, ObjectType obj, BOOL *stop))block NS_AVAILABLE(10_6, 4_0);
typedef NS_OPTIONS(NSUInteger, NSEnumerationOptions) {
NSEnumerationConcurrent = (1UL << 0),
NSEnumerationReverse = (1UL << 1),
};
總結:
1.遍歷collection有四種方式,最基本的是for迴圈,其次是NSEnumerator遍歷法,快速遍歷法,塊列舉法。
2.s塊枚舉發本身就可以通過GCD來併發執行遍歷操作。