The use of iterator patterns in design patterns in the cocoa touch framework _ios

Source: Internet
Author: User

Basic understanding
iterator Mode (iterrator): Provides a method to sequentially access individual elements of an aggregation object without exposing the internal representation of that element.
When you access an aggregation object, and no matter what these objects need to traverse, you should consider using an iterator pattern.
You need to iterate over the aggregation in a variety of ways, you can consider using the iterator pattern.
The iterator pattern is to separate the traversal behavior of the collection object, to abstract out an iterator class to be responsible, so as not to expose the internal structure of the collection, but also to allow the external code to access the data inside the collection transparently.
An iterator defines an interface for accessing the elements of a collection and recording the current element.
Different iterators can perform different iteration strategies.
external iterators and internal iterators:

External iterators

    • The external iterator allows the client to manipulate the iterative process directly, so the client needs to know the external iterator to use it. But it provides more control to the client.
    • Client creates and maintains external iterators
    • Clients can implement multiple types of traversal using different external iterators

Internal iterators

    • The client does not need to know any external iterators, but instead can send messages to each element in the collection, either through the special interface of the collection object, or by accessing an element at a time.
    • The collection object itself creates and maintains its external iterator
    • The collection object can select a different external iterator without modifying the client code

Using iterator mode 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 the enumerator object, which is able to iterate through the various sets-arrays, sets, dictionaries, and 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. collection classes such as Nsarray, Nsset, and Nsdictionary define methods that return an instance of Nsenumerator subclasses corresponding to the collection type. All enumerators work in the same way, and can send a nextobject message to the enumerator in a loop, taking the object from the enumerator until it returns nil to indicate that the traversal is over.
1.NSEnumerator

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

Copy Code code as follows:

Nsarray *array = @[@ "John", @ "Dick", @ "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: John
2015-08-28 16:48:05.463 nsenumatrodemo[ 55301:3712762] Item is: Dick
2015-08-28 16:48:05.464 nsenumatrodemo[55301:3712762] The item is: Harry

Traversal using the Nsenumerator array, when the message calls [Itemenumerator Nextobject] returns nil, and the enumeration process ends.

2. Block-based enumeration

After iOS4.0, new methods are introduced in the Nsarray, Nsdictionary, and Nsset objects for block based enumerations. One of these methods is called Enumerateobjectsusingblock: (void (^) (id obj, Nsuinteger idx, BOOL *stop) block. We can define our own algorithm into a block in the message call, or place a predefined block somewhere else, and pass it to the message call as a parameter. The following code:

Copy Code code as follows:

Nsarray *array = @[@ "John", @ "Dick", @ "Harry"];
NSString *str = @ "Dick";
[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: John
2015-08-28 17:10:03.557 nsenumatrodemo[ 55478:3723216] Item is: Dick
2015-08-28 17:10:03.557 nsenumatrodemo[55478:3723216] Stop traversal

If there is a string "dick" in array arrays, then the pointer *stop is set to Yes to tell the array object to stop the traversal earlier.

The Nsset enumeration in the object is very similar to Nsarray, except that there is no idx parameter in the argument of the block. Because the elements in the collection are unordered.

An important benefit of using internal iterators for Nsarray, Nsdictionary, and Nsset is that the algorithms that handle their content can be defined elsewhere by other developers. Unlike the algorithms defined in the traditional for loop, well-defined blocks can be reused. When blocks become larger, they can be placed in a separate implementation file and not packed with other code.

3. Quick Enumeration

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

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

Copy Code code as follows:

Nsarray *array = @[@ "John", @ "Dick", @ "Harry"];
For (ID item in array) {
NSLog (@ "Item is:%@", item);
}

2015-08-28 17:28:18.619 nsenumatrodemo[55596:3730966] Item is: John
2015-08-28 17:28:18.620 nsenumatrodemo[ 55596:3730966] Item is: Dick
2015-08-28 17:28:18.620 nsenumatrodemo[55596:3730966] The 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 so that each element executes the specified aselector. You can use any of the enumerated methods mentioned above to allow each element to execute the same selector for the same purpose. This method enumerates the collections internally and sends Performselector: messages 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 run-time checking.

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.