Summary of objective-C sets

Source: Internet
Author: User

Objective-C contains nsstring, nsmutablestring, nsarray, nsmutablearray, nsdictionary, and nsmutabledictionary.

First, nsstring, nsarray, and nsdictionary are immutable. Once space is allocated, the length is fixed. The other three classes are variable. After initialization, the space can be dynamically increased and the length is not fixed. These classes have some similarities in initialization and related operations. They can be further understood by putting them together for comparison and learning. Arrays and dictionaries have some special points to note, which are described later, starting from initialization:

String-nsstring

Create literally: nsstring * string = @ "this is a string ";

Format creation: + (ID) stringwithformat :( nsstring *) format ,...;

Example: nsstring * STR = [nsstring stringwithformat: @ "your age is % d, and your height is % d", 26,140];

We can see from the above + number that this is a Class Method

1. Compare the size

Method 1:-(bool) isw.tostring :( nsstring *) astring

It is used to compare the receiver and the string passed as the parameter. A bool (yes or no) is returned to indicate whether the content of the two strings is the same. For example:

NSString *thing1 = @"hello 5";NSString *thing2 = [NSString:stringWithFormat:@"hello %d",5];if([thing1:isEqualToString:thing2]){    NSLog(@"they are the same!");  }

Thing1 = the difference between thing2 and [thing1 isw.tostring: thing2]. The = Operator only checks whether the pointer values of thing1 and thing2 are the same, that is, whether they are the same thing; the latter is used to determine whether the content of two strings is the same

Method 2:-(nscomparisonresult) compare: (nsstring *) astring option: (nsstringcompareoptions) mask;

The compare method compares the received object with the passed string one by one and returns an nscomparisonresult (Enumeration type) to indicate the comparison result. Nscomparisonresult is defined as follows:

enum{    NSOrderedAscending = -1,    NSOrderedSame,    NSOrderedDescending};typedef NSInteger NSComparisonResult

The option parameter is a hidden code. You can add tags by bit or by using the following common tags:

  • Nscaseinsensitivesearch: case-insensitive.
  • Nsliteralsearch: full comparison of case-sensitive characters.
  • Nsnumbericsearch: compares the number of characters of a string, not the string value. If this option is not available, 100 will be placed before 99.

If you need to ignore the case and sort by the number of characters when comparing strings, you should do this:

if([thing1 compare:thing2 option:NSCaseInsensitiveSearch | NSNumerbicSearch] == NSOrderedSame){    NSLog(@"They match!");}
2. String inclusion

Starting with astring:-(bool) hasprefix: (nsstring *) astring;

The end contains (ended with astring):-(bool) hassuffix: (nsstring *) astring;

Contains (contains astring internally):-(nsange) rangeofstring: (nsstring *) astring;

The rangeofstring method returns a nsange struct, which encapsulates the position of string matching and the number of characters that can be matched. For example:

Nsstring * filename = @ "draft-chapter.pages"; nsange range = [filename rangeofstring: @ "chapter"]; // The returned range. Location is 6, range. length is 7

If the passed parameter is not found in the receiving string, the range. Location value is nsnotfound.

Variable string-nsmutablestring

Nsmutablestring is a subclass of nsstring and has a variable length. It is similar to stringbuilder in C #. The declaration is as follows:

+ (ID) stringwithcapacity: (nsuinteger) capacity;

The capacity here is only a recommended value. The actual string size is not limited to the provided capacity.

1. Add a string:
  • -(Void) appendstring: (nsstring *) astring;
  • -(Void) appendformat: (nsstring *) format ,...;

For example:

Nsmutablestring * string = [nsmutablestring stringwithcapacity: 50]; [String appendstring: @ "Hello there"]; [String appendformat: @ "human % d! ", 66]; // The final string value is:" Hello there human 66! "
2. delete a string

Method:-(void) deletecharactersinrange :( nsange) arange;

Nsmutablestring * Friends = [nsmutablestring stringwithcapacity: 50]; [friends appendstring: @ "James bethlynn Jack Evan"]; nsange jackrange = [friends rangeofstring: @ "Jack"]; jackrange. length ++; [friends deletecharactersinrange: jackrange]; // the final result is: "James bethlynn Evan"

Nsmutablestring is a subclass of nsstring, so nsmutablestring can be used in any place where nsstring is used. For example, we can add a formatted string:

Nsmutablestring * string = [nsmutablestring stringwithformat: @ "Jo % dy", 2]; // The value of string is "jo2y"

Immutable array-nsarray

Nsarray is a cocoa class, which is more powerful than C and C ++ arrays. nsarray can store any type of objects, such as strings, custom types, and even other arrays or dictionaries, but remember: nsarray can only save objects, such as int, Char, double, and other basic data types, but cannot be saved directly. You must convert them to an object before adding them to an array. In addition, nsarray is an unchangeable array. Once it is created, its length is fixed and no elements can be added or deleted. Of course, the objects contained in the array can be changed, however, the array object itself remains unchanged.

Nsarray creation:

  • 1. nsarray * array = [[nsarray alloc] initwithobjects: @ "1", @ "2", @ "3", nil];
  • 2. nsarray * array1 = [nsarray arraywitharray: array]; (create an array with an existing array)
  • 3. nsarray * array2 = [nsarray arraywithobjects: @ "one", @ "two", @ "three", nil]; // The Object List must end with nil
  • 4. nsarray * array3 = @ [@ "one", @ "two", @ "three"]; // when a string is created, you do not have to add nil at the end.

Related methods:

-(Nsuinteger) count; // gets the number of objects in the array

-(ID) objectatindex :( nsuinteger) index; // gets the object at the specified index

You can also access the array literally, for example, Id * myobject = array [1]; we can use the count and value to traverse the objects in the array:

// Method 1 nsuinteger COUNT = [array count]; for (nsuinteger I = 0; I <count; I ++) {nslog (@ "index % d has % @. ", I, [array objectaiindex: I]);} // method 2 for (nsuinteger J = 0; j <count; j ++) {nslog (@ "index % d has % @", J, array [J]);}

Nsarray also has a special creation method by splitting strings. The method declaration is as follows:

-(Nsarray) componentsseparatedbystring :( nsstring *) Separater;

For example: nsstring * string = @ "Oop: ACK: Bork: greeble: ponies ";

Nsarray * chunks = [String componentsseparatedbystring: @ ":"];

You can also use the specified string to combine the elements in nsarray to create a string. For example:

String = [chunks componentsjoinedbystring: @ "+"]; // The content of string is: "Oop + ACK: Bork + greeble + ponies"

Variable array-nsmutablearray

Nsmutablearray creation: + (ID) arraywithcapacity :( nsuinteger) numitems;

Like the stringwithcapacity method in nsmutablestring, the capacity here is only a recommended value. When the capacity exceeds the capacity, the variable array can dynamically expand the space.

Add an object at the end:-(void) addobject :( ID) anobject;

Insert an object at the specified index:-(void) insertobject :( ID) anobject atindex :( nsuinteger) index; // The elements following the index are moved to the backend.

Delete the object at the specified index:-(void) removeobjectatindex :( nsuinteger) index;

Delete all objects:-(void) removeallobjects;

Nsmutablearray * array = [nsmutablearray arraywithcapacity: 17]; // create for (nsinteger I = 0; I <4; I ++) // Add four objects at the end {tire * tire = [Tire new]; [array addobject: Tire];}
Tire * t = [Tire new];
[Array insertobject: T atindex: 1]; // Add an object [array removeobjectatindex: 1] at the second position; // delete an object with an index of 1, namely: second object
[Array removeallobjects];
Unchangeable dictionary-nsdictionary

Like the dictionary in C #, nsdictionary in objective-C can store a value under a given keyword (usually an nsstring string), and then you can use this keyword to find the corresponding data. Compared with arrays, the dictionary uses the key query optimization method, which can immediately find the data to be searched without traversing the entire array. For frequent queries and large datasets, dictionary usage is much faster than array usage.

Like nsstring and nsarray, nsdictionary is also unchangeable. When creating a new nsdictionary, all objects and keywords stored in the dictionary must be provided.

Basic operations:

1. Creation Method 1: using a literal method, such as @ {key: value ,...}

2. Creation Method 2: using the dictionarywithobjectsandkeys method, this method accepts the sequence of alternating objects and keywords, and uses the nil value as the termination symbol, which is defined as follows:

+ (ID) dictionarywithobjectsandkeys :( ID) firstobject ,...

3. Method 1: Use objectforkey to receive a keyword and use this keyword to obtain the corresponding data. The method is defined as follows:

-(ID) objectforkey :( ID) akey;

4. Method 2: dictionary [Key];

The sample code is as follows:

1 tire * tire1 = [Tire new]; 2 tire * tire2 = [Tire new]; 3 tire * tire3 = [Tire new]; 4 tire * tire4 = [Tire new]; 5 nsdictionary * tires = [nsdictionary dictionarywithobjectsandkeys: tire1, @ "front-left", tire2, @ "front-Right", tire3, @ "back-left", tire4, @ "back-right", nil]; 6 // 7 nsdictionary * tires = @ {@ "front-left": tire1, @ "front-Right ": tire2, @ "back-left": tire3, @ "back-right": tire4}; 8 9 // obtain method 1 10 tire * tire = [Tires objectforkey: @ "front-left"]; 11 // method 2 12 tire * tire = tires [@ "front-left"];
Variable dictionary-nsmutabledictionary

You can create a new nsmutabledictionary object by sending a dictionary message to the nsmutabledictionary class, or you can use the dictionarywithcapacity: method to create a variable dictionary object with the initial size. The definition of this method is as follows:

+ (ID) dictionarywithcapacity :( nsuinteger) numitems;

Like the nsmutablestring and nsmutablearray mentioned earlier, the dictionary capacity is only a recommended value, not a limit on its size.

You can use the setobject: forkey: Method to add elements to the dictionary. The definition is as follows:

-(Void) setobject :( ID) andobject forkey :( ID) akey;

If you use setobject: forkey: Method for the existing keywords in the dictionary, this method replaces the original data with a new value. To delete some keywords, you can use the removeobjectforkey method, which is defined as follows:

-(Void) removeobjectforkey :( ID) akey;

The sample code is as follows:

1 // create a dictionary object with the initial length of 10 2 nsmutabledictionary * tires = [nsmutabledictionary dictionarywithcapacity: 10]; 3 // nsmutabledictionary * tires = [nsmutabledictionary dictionary]; 4 5 // Add element 6 dynamically [Tires setobject: tire1: forkey: @ "front-left"]; 7 [Tires setobject: tire2: forkey: @ "front-Right"]; 8 [Tires setobject: tire3: forkey: @ "back-left"]; 9 [Tires setobject: tire4: forkey: @ "back-right"]; 10 11 // Delete element 12 [Tires removeobjectforkey: @ "back-left"];

 

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.