iOS design mode-iterator mode

Source: Internet
Author: User

What is the iterator pattern?

Iterators provide a way to sequentially access elements in a collection object without the underlying representations and details of a burst structure. The function of traversing elements in the collection is transferred from the collection itself to the iterator object. An iterator defines an interface that accesses a collection element and records the current element. Different iterators can perform different policies.

When to use the iterator pattern?

@: The content of the combined object needs to be accessed without leaking its internal representation.

@: You need to traverse a group of objects in several ways.

@: You need to provide a unified interface for traversing various types of composite objects.

Using the iterator pattern in the cocoa touch framework?

The Nsenumerator class in the underlying framework implements the iterator pattern. The private concrete subclass of the abstract Nsenumerator class returns an enumerator object that can sequentially traverse various collections-arrays, collections, dictionaries-to return the objects in the collection to the client.

Nsdirectoryenumerator, an instance of this class recursively enumerates the contents of a directory in the file system. A collection class such as Nsarray, Nsset, Nsdictionary, defines a method that returns an instance of the Nsenumerator subclass corresponding to the collection type. All enumerators work in the same way, sending an nextobject message to the enumerator in a loop, taking the object from the enumerator until it returns nil to indicate the end of the traversal.

1.NSEnumerator

We can use Nsenumerator to enumerate the elements in the Nsarray, Nsdictionary, and Nsset objects. Nsenumerator itself is an abstract class that relies on several factory methods, such as Objectenumrator or keyenumerator, to create and return the corresponding specific enumerator object. The code is as follows:

Nsarray *array = @[@ "Zhang San", @ "John Doe", @ "Harry"];        Nsenumerator *itemenumerator = [array objectenumerator];    NSString *item;    while (item = [Itemenumerator Nextobject]) {NSLog (@ "Item is:%@", item); }
2015-08-28 16:48:05.463 nsenumatrodemo[55301:3712762] Item is: Zhang San 2015-08-28 16:48:05.463 nsenumatrodemo[55301:3712762 ] Item is: John Doe 2015-08-28 16:48:05.464 nsenumatrodemo[55301:3712762] Item is: Harry

use Nsenumerator to iterate through the array, and when the message calls [Itemenumerator Nextobject] returns nil, then the enumeration process ends.

2. Block-based enumeration

From iOS4.0, a new method is introduced in the Nsarray, Nsdictionary, and Nsset objects for block-based enumeration. One of the methods is called Enumerateobjectsusingblock: (void (^) (id obj, Nsuinteger idx, BOOL *stop)) block. We can embed our algorithm into a block within a message call, or predefine a block somewhere else, and then pass it as a parameter to a message call. The following code:

nsarray *array = @[@ "Zhang San",  @ "John Doe",  @ "Harry"]; nsstring *str = @ "John Doe"; [array enumerateobjectsusingblock:^ (Id obj, nsuinteger idx, bool *stop)  {      nslog (@ "item is :%@",  obj);              if  ([obj localizedstandardcompare:str] ==  Nsorderedsame)  {         *stop = YES;          nslog (@ "Stop traversal");      }]; 
2015-08-28 17:10:03.556 nsenumatrodemo[55478:3723216] Item is: Zhang San 2015-08-28 17:10:03.557 nsenumatrodemo[55478:3723216 ] Item is: John Doe 2015-08-28 17:10:03.557 nsenumatrodemo[55478:3723216] Stop traversal

if the array array has the string "John Doe", then the pointer *stop is set to Yes to notify the array object to stop the traversal prematurely.

Block-based enumerations in Nsset objects are very similar to those in Nsarray, except that there is no idx parameter in the parameters of the block. Because the elements in the collection are unordered.

An important benefit of using an internal iterator for Nsarray, Nsdictionary, and Nsset is that the algorithm that handles its content can be defined elsewhere by other developers. Unlike the algorithm defined in the traditional for loop, a clearly defined block can be reused. As the blocks become larger, they can be placed in a separate implementation file and not squeezed with other code.

3. Quick Enumeration

An enumeration, quick enumeration, and an enumeration method recommended by Apple are provided after iOS2.0. It allows the enumeration of collection objects to be used directly as part of a for loop, without the use of other enumeration objects, and is more efficient than a for loop for a traditional opportunity index. Enumerating loops now uses pointer arithmetic to make it more efficient than the standard method of using Nsenumerator.

To use fast enumeration, the collection class needs to implement the Nsfastenumeration protocol to provide the runtime with the necessary information about the collection. All collection classes in the underlying framework and the Nsenumerator class support fast enumeration. Therefore, you do not have to use the while loop to enumerate each element from Nsenumerator until Nextobject returns nil. The code is as follows:

Nsarray *array = @[@ "Zhang San", @ "John Doe", @ "Harry"];    For (the ID item in the array) {NSLog (@ "Item is:%@", item); }
2015-08-28 17:28:18.619 nsenumatrodemo[55596:3730966] Item is: Zhang San 2015-08-28 17:28:18.620 nsenumatrodemo[55596:3730966 ] Item is: John Doe 2015-08-28 17:28:18.620 nsenumatrodemo[55596:3730966] Item is: Harry

4. Internal enumeration

Nsarray has an instance method called (void) Makeobjectsperformselector: (SEL) Aselector, which allows the client to send a message to each element in the array, allowing each element to execute the specified aselector. You can use any one of the enumeration methods mentioned earlier to have each element execute the same selector for the same purpose. This method internally enumerates the collection and sends a performselector: message to each element. The disadvantage of this approach is that if any element in the collection does not respond to the selector, an exception is thrown. It is therefore primarily used for simple operations that do not require too much runtime checking.


This is the iterator pattern.

iOS design mode-iterator mode

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.