Various traversal (iterations) modes in iOS learning 6.objective-c

Source: Internet
Author: User
Tags allkeys gcd

Description: Turn to the top of the text

First, use for loop

To iterate through a dictionary, an array, or a collection, the For loop is the simplest and most convenient way to use it.

-(void) iteratorwithfor{//////////working with arrays//////////Nsarray *arraym = @[@"1",@"2",@"3",@"4"]; Nsinteger Arraymcount=[Arraym Count];  for(inti =0; i<arraymcount; i++) {NSString*obj =Arraym[i]; NSLog (@"%@", obj); }        //////////Processing Dictionaries//////////Nsdictionary *DICTM = @{@"1":@" One",@"2":@" Both",@"3":@"three"}; Nsarray*dictkeysarray =[DICTM AllKeys];  for(inti =0; i<dictkeysarray.count; i++) {NSString*key =Dictkeysarray[i]; NSString*obj =[DICTM Objectforkey:key]; NSLog (@"%@:%@", Key,obj); }        //////////Process Collection//////////Nsset * Setm = [[Nsset alloc] Initwithobjects:@" One",@" Both",@"three",@" Four", nil]; Nsarray*setobjarray =[Setm allobjects];  for(inti =0; i<setobjarray.count; i++) {NSString*obj =Setobjarray[i]; NSLog (@"%@", obj); }        //////////Reverse Traversal----DESCENDING traversal----take an array as an exampleNsarray *arraym2 = @[@"1",@"2",@"3",@"4"]; Nsinteger ArrayMCount2= [ArrayM2 Count]-1;  for(Nsinteger i = ArrayMCount2; i>0; i--) {NSString*obj =Arraym2[i]; NSLog (@"%@", obj); }}

Advantages: Simple

Cons: Because dictionaries and sets are unordered inside, we need to use a new "array" as an intermediary to iterate over the dictionaries and collections, with a portion of the expense

Second, using for...in traversal

In Objective-c 2.0, a fast traversal of the for...in form is added, which is a simple syntax and a fast speed.

 // --> handles array  nsarray *arraym = @[< Span style= "color: #800000;" >@ " 1  " ,  2  " ,  3  " ,  4  "   for  (id  obj in   Arraym) {NSLog ( @ " %@   ,obj); }

//--Working with dictionaries (ordered)Nsdictionary *DICTM = @{@"1":@" One",@"2":@" Both",@"3":@"three",@"4":@" Four"}; Nsarray*array =[DICTM AllKeys]; Nsarray*sortarray = [Array Sortedarrayusingcomparator:^nscomparisonresult (ID_nonnull Obj1,ID_nonnull Obj2) {        return[Obj1 compare:obj2 Options:nsnumericsearch];    }];  for(IDObjinchSortarray) {NSLog (@"%@", Dictm[obj]); }

Pros: 1) Simple syntax, 2) Highest efficiency

Disadvantage: Unable to get subscript for the current traversal operation.

Three, block-based traversal mode

A block-based approach to traversal is the newest method introduced. It provides best practices for iterating through the array of data types such as dictionaries.

-(void) iteratorwithblock{//-- working with arraysNsarray *arraym = @[@"1",@"2",@"3",@"4"]; [Arraym Enumerateobjectsusingblock:^(ID_nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) {NSLog (@"%zd--%@", Idx,obj);    }]; //-- working with dictionariesNsdictionary *DICTM = @{@"1":@" One",@"2":@" Both",@"3":@"three",@"4":@" Four"}; [DICTM Enumeratekeysandobjectsusingblock:^(ID_nonnull Key,ID_nonnull obj, BOOL *_nonnull stop) {NSLog (@"%@:%@", Key,obj);    }]; //-- working with collectionsNsset *setm = [[Nsset alloc]initwithobjects:@" One",@" Both",@"three",@" Four", nil]; [Setm Enumerateobjectsusingblock:^(ID_nonnull obj, BOOL *_nonnull stop) {NSLog (@"%@", obj);    }]; //--Reverse traversal---descending traversal---take an array as an exampleNsarray *arraym2 = @[@"1",@"2",@"3",@"4"]; [ArrayM2 enumerateobjectswithoptions:nsenumerationreverse Usingblock:^(ID_nonnull obj, Nsuinteger idx, BOOL *_nonnull stop) {NSLog (@"%zd--%@", Idx,obj); }];}

Pros: 1) You can get all the information you need directly from the block, including subscript, value, etc. Especially relative to dictionaries, you don't need to do extra coding to get the value of both key and value.

2) The ability to directly modify the type of the key or obj in the block as the real type, can eliminate the work of type conversion.

3) The concurrency iteration function can be turned on by Nsenumerationconcurrent enumeration values.

Description: Block-based traversal is also very simple when implementing a reverse traversal, using the Enumerateobjectswithoptions method, passing nsenumerationreverse as a parameter, when processing a traversal operation based on block Traversal mode.

Iv. using the Dispatch_apply function in GCD

The use of the Dispatch_apply function in GCD also enables the traversal of dictionaries, arrays, and so on, which is more suitable for dealing with situations that take a long time and have many iterations. Examples are as follows:

-(void) iteratorwithaplly{//-- working with arraysNsarray *arraym = @[@"1",@"2",@"3",@"4"]; //Get global concurrency queuedispatch_queue_t queue = Dispatch_get_global_queue (0,0); Dispatch_apply (Arraym.count, queue,^(size_t index) {NSLog (@"%@---%@", Arraym[index],[nsthread CurrentThread]); });}

Advantage: Open multiple threads concurrently processing traverse task, the execution is high efficiency.

Cons: 1) The processing of dictionaries and collections requires an array; 2) cannot implement a reverse traversal.

Various traversal (iterations) modes in iOS learning 6.objective-c

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.