Collection class for iOS objects (collection classes)

Source: Internet
Author: User
Tags scalar
<span id="Label3"></p><p><p>When you start writing code for your app, you'll find a lot of objective-c framework classes available, especially the basic framework class, which provides basic services for all of the Platform's Applications. The underlying framework class includes a value class (value classes) that represents basic data types such as strings and numbers, and a collection class (collection classes) that stores other Objects. You'll be relying on value classes and collection classes to write a lot of code for your ToDoList app.</p></p><strong><strong>Value Object (Objects)</strong></strong>The foundation framework provides classes that generate strings, binary data, date and time, numbers, and other value Objects. The value object encapsulates the basic data types in the C language and provides methods for manipulating the corresponding data types. In program calls, you often encounter methods and functions that use value objects as parameters or return Values. Different parts of the framework, and even between different frameworks, can pass data through value object Classes. Examples of value objects in the foundation Framework: •<span class="Apple-tab-span"><span class="Apple-tab-span">NSString and Nsmutablestring</span></span>•<span class="Apple-tab-span"><span class="Apple-tab-span">NSData and Nsmutabledata</span></span>•<span class="Apple-tab-span"><span class="Apple-tab-span">NSDate</span></span>•<span class="Apple-tab-span"><span class="Apple-tab-span">NSNumber</span></span>•<span class="Apple-tab-span"><span class="Apple-tab-span">Nsvalue</span></span>Because value objects represent scalar values, you can use them in the collection class and any other classes that you Need. The value object allows you to manipulate the values it encapsulates more easily and efficiently than the primitive data it encapsulates. In the case of the NSString class, it contains methods such as finding and replacing substrings, writing a string to a file or url, and constructing a file system path using a String. You can use the primitive data to create a value object (if necessary, pass it as a parameter to a METHOD) and then access the encapsulated data through the Object. The following is a NSNumber class to illustrate how to create a value object Above. <ol class="dp-c"> <ol class="dp-c"> <li class="alt"><span class="keyword">int n = 5; <span class="comment">//Value assigned to primitive type</span></span></li> <li>NSNumber *numberobject = [nsnumber numberwithint:n]; <span class="comment">//Value object created from primitive type</span></li> <li class="alt"><span class="keyword">int y = [numberobject intvalue]; <span class="comment">//encapsulated value obtained from value object (y = = N)</span></span></li> </ol> </ol>Most value classes create instances of them by declaring initializers and class factory METHODS. The class factory method can complete the assignment and initialization of an instance, returning a created Object. For example, the NSString class declares a string class method that can allocate and initialize a new instance of the class and use it as the return value returned to your Code. <ol class="dp-c"> <ol class="dp-c"> <li class="alt">NSString *string = [nsstring string];</li> </ol> </ol>In addition to creating value objects and letting you access the values they encapsulate, most value classes provide simple ways to manipulate objects, such as Object Comparisons.<strong><strong>string</strong></strong>OBJECTIVE-C supports the same conventions as the C language to specify Strings: single quotes for individual characters, double quotation marks for strings, but the OBJECTIVE-C framework generally does not use C strings, which typically use NSString Objects. The NSString class provides the encapsulation of a string with the following advantages: the built-in memory management feature can store strings of any length, support different character encodings (especially unicode), and character formatting methods. Because you often use such strings, objective-c provides an easy way to create NSString objects from constant Values. To use this constant, you can precede the double quotation mark of the string with an @ symbol, as shown in the following example. <ol class="dp-c"> <ol class="dp-c"> <li class="alt"><span class="comment">Create the string "My string" plus carriage Return.</span></li> <li>NSString *mystring = @<span class="string">"My string\n";</span></li> <li class="alt"><span class="comment">Create the formatted string "1 string".</span></li> <li>NSString *anotherstring = [nsstring stringwithformat:@<span class="string">"%d%@", 1, @<span class="string">"String"];</span> </span></li> <li class="alt"><span class="comment">Create a objective-c string from a C string.</span></li> <li>NSString *fromcstring = [nsstring stringwithcstring:<span class="string">"A C string" encoding:nsutf8stringencoding];</span></li> </ol> </ol><strong><strong>Digital</strong></strong>OBJECTIVE-C provides simplified notation for creating nsnumber objects, removing the need to call initializers or class factory methods to create these Objects. Simply precede the value with the @ sign, and you can add a type indicator after the Value. For example, to create a NSNumber object that encapsulates integer and double values, you need to write the following code: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">NSNumber *myintvalue = @32;</li> <li>NSNumber *mydoublevalue = @3.22346432;</li> </ol> </ol>You can even use nsnumber represented to create an object that encapsulates a Boolean type and character type, as Follows: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">NSNumber *myboolvalue = @YES;</li> <li>NSNumber *mycharvalue = @<span class="string">' V ';</span></li> </ol> </ol>You can create NSNumber objects that represent unsigned integers, long integers, super-long integers, and floating-point types by using the u, L, LL, and F Suffixes. The following code example creates a NSNumber object that encapsulates a floating-point value type: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">NSNumber *myfloatvalue = @3.2f;</li> </ol> </ol><strong><strong>Collection Object</strong></strong>Most of the collection objects in Objective-c are instances of these basic collection classes, nsarray, nsset, and Nsdictionary. These classes are used to manage group objects, so the instance you add to the collection must be a objective-c class. If you need to add a scalar value, you must create an appropriate NSNumber or nsvalue instance to represent it. The member objects stored in the collection cannot be destroyed until the collection is Destroyed. This is because the collection class uses strong references to maintain its member Objects. In addition to tracking and maintaining its objects, the collection class provides functions such as enumerating, accessing specific objects, and judging whether an object is within a Collection. nsarray, the contents of the Nsset and Nsdictionary classes are initialized at the time the collection is created, and can no longer be changed in use, which is called an immutable class. Each collection class has a mutable subclass that allows you to arbitrarily add a delete member Object. Different collection classes organize their member objects in different ways: •<span class="Apple-tab-span"><span class="Apple-tab-span">Nsarray and Nsmutablearray-stores An array of ordered OBJECTS. You can access a member object by specifying a location in the Array. The index of the first element in the array is 0. </span></span>•<span class="Apple-tab-span"><span class="Apple-tab-span">Nsset and Nsmutebleset-stores a collection of unordered objects. Each element has uniqueness in the Collection. You can only access the objects in the collection by testing or filtering the METHOD. </span></span>•<span class="Apple-tab-span"><span class="Apple-tab-span">nsdictionary and nsmutabledictionary-a dictionary stored by Key-value pairs. A key is a unique identifier, usually a string, and the value is the object you want to Store. You can access the object by specifying the KEY. </span></span><strong><strong>Array</strong></strong>An array (nsarray) is used to represent a set of ordered objects, and the only requirement is that each object must be an objective-c object, and that each object is not an instance of the same class that is not Required. To maintain the order of the array, the Element's index starts at 0, as shown in: creating an array is the same as the value class described earlier in this chapter, and you can create an array by assigning and initializing, factory methods, or array constants. Depending on the number of objects, there are many initialization and factory methods to Use: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">+ (id) arraywithobject: (id) anobject;</li> <li>+ (id) arraywithobjects: (id) firstobject, ...;</li> <li class="alt">-(id) initwithobjects: (id) firstobject, ...;</li> </ol> </ol>Because Arraywithobjects: and Initwithobjects: methods are variable parameter lengths and end with nil, initialize as shown in the following code: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">Nsarray *somearray =</li> <li>[nsarray arraywithobjects:someobject, somestring, somenumber, somevalue, nil];</li> </ol> </ol>The previous example creates an array similar to the previous one, where the index value of the first object someobject is 0, and the last object somevalue the index value is 3. If one of the values in the middle is nil, the array may be truncated. <ol class="dp-c"> <ol class="dp-c"> <li class="alt">ID firstobject = @<span class="string">"somestring";</span></li> <li>ID secondobject = nil;</li> <li class="alt">ID thirdobject = @<span class="string">"anotherstring";</span></li> <li>Nsarray *somearray =</li> <li class="alt">[nsarray arraywithobjects:firstobject, secondobject, thirdobject, nil];</li> </ol> </ol>In this case, Somearray contains only firstobject, because the value of Secondobject is nil and therefore is treated as the Terminator of the Array. You can use the following simple syntax to create an array constant: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">Nsarray *somearray = @[firstobject, secondobject, thirdobject];</li> </ol> </ol>When using this syntax, do not use nil to end the list of objects, in fact, Nil is a nonexistent value. For example, you get a run exception when you execute the following code: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">ID firstobject = @<span class="string">"somestring";</span></li> <li>ID secondobject = nil;</li> <li class="alt">Nsarray *somearray = @[firstobject, secondobject];</li> <li><span class="comment">Exception: "attempt to insert nil object"</span></li> </ol> </ol>After a query array object has created an array, you can query for information such as how many objects it contains, or whether it contains a given object. <ol class="dp-c"> <ol class="dp-c"> <li class="alt">Nsuinteger Numberofitems = [somearray count];</li> <li></li> <li class="alt"><span class="keyword">If ([somearray containsobject:somestring]) {</span></li> <li>...</li> <li class="alt">}</li> </ol> </ol>You can also query an Array's items by a given index, and if you try to request a nonexistent index, you will get an out-of-bounds exception at run Time. To prevent exceptions, first check the number of items in the array before you use Them. <ol class="dp-c"> <ol class="dp-c"> <li class="alt"><span class="keyword">If ([somearray count] > 0) {</span></li> <li>NSLog (@<span class="string">"first item is:%@", [somearray objectatindex:0]);</span></li> <li class="alt">}</li> </ol> </ol>This example checks to see if the number of objects is greater than 0, and if so, the foundation framework function NSLog outputs the description of the first element in an array with an index of 0. Another way is to use objecatindex, you can also like the C language, using square brackets Syntax query array elements, The previous example can be written like this: <ol class="dp-c"> <ol class="dp-c"> <li class="alt"><span class="keyword">If ([somearray count] > 0) {</span></li> <li>NSLog (@<span class="string">"first item is:%@", somearray[0]);</span></li> <li class="alt">}</li> </ol> </ol>Array object ordering the Nsarray class provides a series of methods for ordering Objects. Because Nsarray are immutable, these methods return a new array that contains the sorted object. For example, you can sort a string array by calling the Compare: method on each string: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">Nsarray *unsortedstrings = @[@<span class="string">"gammastring", @<span class="string">"alphastring", @<span class="string">"betastring"];</span> </span> </span></li> <li>Nsarray *sortedstrings =</li> <li class="alt">[unsortedstrings sortedarrayusingselector: @selector (compare:)];</li> </ol> </ol>Variability Although the Nsarray class itself is immutable, it can contain mutable objects, for example, You can add a mutable string to an immutable array, as Follows: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">nsmutablestring *mutablestring = [nsmutablestring stringwithstring:@<span class="string">"Hello"];</span></li> <li>Nsarray *immutablearray = @[mutablestring];</li> </ol> </ol>You can then change the contents of the string as you Wish. <ol class="dp-c"> <ol class="dp-c"> <li class="alt"><span class="keyword">If ([immutablearray count] > 0) {</span></li> <li>ID string = immutablearray[0];</li> <li class="alt"><span class="keyword">if ([string iskindofclass:[nsmutablestring <span class="keyword">class]]) {</span> </span></li> <li>[string appendstring:@<span class="string">"world!"];</span></li> <li class="alt">}</li> <li>}</li> </ol> </ol>If you want to add or remove objects from an array after the array is created, you can use nsmutablearray, which adds a series of methods to add a delete, replace one or more objects. <ol class="dp-c"> <ol class="dp-c"> <li class="alt">Nsmutablearray *mutablearray = [nsmutablearray array];</li> <li>[mutablearray addobject:@<span class="string">"gamma"];</span></li> <li class="alt">[mutablearray addobject:@<span class="string">"alpha"];</span></li> <li>[mutablearray addobject:@<span class="string">"beta"];</span></li> <li class="alt"></li> <li>[mutablearray replaceobjectatindex:0 withobject:@<span class="string">"epsilon"];</span></li> </ol> </ol>This example creates an array of objects @ "epsilon", @ "alpha" and @ "beta". For a mutable array, you can sort the arrays without generating a new array, as Follows: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">[mutablearray sortusingselector: @selector (caseinsensitivecompare:)];</li> </ol> </ol>In this example, the array elements are sorted in ascending order and are not Case-sensitive.<strong><strong>Set</strong></strong>The set object is similar to an array, but it contains unordered objects. Because sets are unordered, performance is better than arrays when testing member Objects. The set is immutable, so its contents must be specified at the time of Creation. <ol class="dp-c"> <ol class="dp-c"> <li class="alt">Nsset *simpleset =</li> <li>[nsset setwithobjects:@<span class="string">"Hello, world!", @42, avalue, anobject, nil];</span></li> </ol> </ol>Like the Nsarray class, initwithobjects: and setwithobjects: The method is a variable-length parameter and must end with Nil. The variable subclass of the Nsset is Nsmutableset. Each set of objects is stored only once, even if you add an object more than Once. <ol class="dp-c"> <ol class="dp-c"> <li class="alt">NSNumber *number = @42;</li> <li>Nsset *numberset =</li> <li class="alt">[nsset setwithobjects:number, number, number, number, nil];</li> <li><span class="comment">//numberset only contains one object</span></li> </ol> </ol><strong><strong>Dictionaries</strong></strong>Unlike the simple maintenance of an ordered or unordered collection object, the dictionary (nsdictionary) accesses the object using the given Key-value pair, which can be used for retrieval. The string object is typically used as the key to the Dictionary. Although you can use other objects as keys, keep in mind that each key is copied into the dictionary, so the object must support the Nscopying Method. however, if you want to encode using Key-value pairs, you must use String key as the Dictionary object (see Key-value Coding Programming Guide for Details). To create a dictionary you can use Alloc and initialize, or the factory method of the class to create the dictionary as Follows: <ol class="dp-c"> <li class="alt"><li class="alt">Nsdictionary *dictionary = [nsdictionary dictionarywithobjectsandkeys:</li></li> <li><li>someobject, @<span class="string">"anobject",</span></li></li> <li class="alt"><li class="alt">@<span class="string">"Hello, world!", @<span class="string">"hellostring",</span> </span></li></li> <li><li>@42, @<span class="string">"magicnumber",</span></li></li> <li class="alt"><li class="alt">somevalue, @<span class="string">"avalue",</span></li></li> <li><li>nil];</li></li> </ol>For Dictionarywithobjectsandkeys: and initwithobjectsandkeys: methods, each object must be declared before the key and end with Nil. OBJECTIVE-C provides a simple syntax for dictionary constant creation: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">Nsdictionary *dictionary = @{</li> <li>@<span class="string">"anobject": someobject,</span></li> <li class="alt">@ "<span class="string">hellostring": @<span class="string">"Hello, world!",</span> </span></li> <li>@<span class="string">"magicnumber": @42,</span></li> <li class="alt">@<span class="string">"avalue": somevalue</span></li> <li>};</li> </ol> </ol>For dictionary constants, keys are specified before the object, and list objects and keys do not have to end with Nil. After the dictionary is created in the query dictionary, you can query the object for the key, as Follows: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">NSNumber *storednumber = [dictionary objectforkey:@<span class="string">"magicnumber"];</span></li> </ol> </ol>If the object is not found, the Objectforkey: method returns Nil. In addition to the objectforkey: method, you can also query using the following methods: <ol class="dp-c"> <ol class="dp-c"> <li class="alt">NSNumber *storednumber = dictionary[@<span class="string">"magicnumber"];</span></li> </ol> </ol>Variability if you need to add or delete content after the dictionary is created, use the nsmutabledictionary class. <ol class="dp-c"> <ol class="dp-c"> <li class="alt">[dictionary setobject:@<span class="string">"another string" forkey:@<span class="string">"secondstring"];</span> </span></li> <li>[dictionary removeobjectforkey:@<span class="string">"anobject"];</span></li> </ol> </ol><strong><strong>use Nsnull to represent nil</strong></strong>You cannot add nil to the collection class described in this section because nil represents a "nonexistent object" in objective-c, and if you need to represent an object that does not exist in the collection, use the Nsnull class. <ol class="dp-c"> <ol class="dp-c"> <li class="alt">Nsarray *array = @[@<span class="string">"string", @42, [NSNull <span class="keyword">null]];</span> </span></li> </ol> </ol>In nsnull, a null method always returns the same instance, and a class with such behavior is called a "skeleton class" (singleton classes). You can use the following methods to check whether an object equals nsnull: <ol class="dp-c"> <ol class="dp-c"> <li class="alt"><span class="keyword">For (id object in <span class="keyword">array) {</span></span></li> <li><span class="keyword">if (object = = [NSNull <span class="keyword">null]) {</span> </span></li> <li class="alt">NSLog (@<span class="string">"Found a null object");</span></li> <li>}</li> <li class="alt">}</li> </ol> </ol>Although the foundation framework contains much more functionality than is described here, you don't need to master every detail of it now. If you want to learn more about the foundation framework, see the Foundation framework Reference. Now that you have enough information to continue implementing the ToDoList application, you need to write a custom data class in order to implement it.<p><p>Collection class for iOS objects (collection classes)</p></p></span>
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.