OC learning --- NSArray and NSMutableArray in the Foundation framework, nsarray

Source: Internet
Author: User

OC learning --- NSArray and NSMutableArray in the Foundation framework, nsarray

In a previous article, we introduced the NSString class and NSMutableString class in the Foundation framework:

Http://blog.csdn.net/jiangwei0910410003/article/details/41788223

Today, let's continue to look at the NSArray class and NSMutableArray class in the Foundation framework. In fact, the NSArray class is similar to the List class in Java. It is a data structure. Of course, we can see from these two classes, the NSArray class is unchangeable, And the NSMutableArray class is variable. Next let's take a look at the NSArray class.


I. NSArray class

//// Main. m // 16_NSArray /// Created by jiangwei on 14-10-12. // Copyright (c) 2014 jiangwei. all rights reserved. // # import <Foundation/Foundation. h> // NSArray cannot store basic data types. It can only store class instances. If you need to put basic types and struct into an array, // data encapsulation must be performed through NSNumber/NSValue, and nilint main (int argc, const char * argv []) {@ autoreleasepool {// 1 cannot be stored in NSArray. --------------------- NSString * s1 = @ "zhangsan"; NSString * s2 = @ "lisi"; NSString * s3 = @ "wangwu "; // The final nil is equivalent to the ending mark NSArray * array1 = [[NSArray alloc] initWithObjects: s1, s2, s3, nil]; // when printing, the description method is called // equivalent to: array1.description NSLog (@ "% @", array1); // use the class method to create array1 = [NSArray arrayWithObjects: s1, s2, s3, nil]; // create an array and put the data in the source array into NSArray * array2 = [NSArray arrayWithArray: array1]; // 2. ---------------------- objectAtIndex // access the data in the array. The array stores the NSString * str1 = [array1 objectAtIndex: 0]; // 3. ---------------------- count // obtain the number of NSUInteger count = [array1 count] in the array element; // return an unsigned value // 4. ---------------------- containsObject // determines whether the array contains an object and determines the pointer object value, not the value BOOL isContains = [array1 containsObject: @ "zhangsan"]; // 5. ---------------------- indexOfObject // return the value of an object in the array NSUInteger index = [array1 indexOfObject: @ "zhangsan"]; if (index = NSNotFound) {// not found} else {// found} // 6. ---------------------- if a string is stored in the componentsJoinedByString // array, you can use a connector to connect all its elements. // note that the elements in the array must be strings NSString * content = [array1 componentsJoinedByString: @ ","]; // 7. ---------------------- lastObject // access the last element of the array NSString * lastObj = [array1 lastObject]; // 8. ---------------------- arrayByAddingObject // append an element after the original array and return a new array object because it is an immutable NSArray * array3 = [array1 arrayByAddingObject: @ "zhaoliu"]; // array traversal for (int I = 0; I <array1.count; I ++) {NSString * str = [array1 objectAtIndex: I]; NSLog (@ "% @", str);} // fast traversal for (NSString * s in array1) {NSLog (@ "% @", s);} // After xcode4.4, the compiler optimizes the NSArray * array7 = @ [s1, s2, s3]; NSString * s = array7 [0];} return 0 ;}
Let's take a look at his operation method:

1. Create NSArray

// 1. --------------------- NSString * s1 = @ "zhangsan"; NSString * s2 = @ "lisi"; NSString * s3 = @ "wangwu "; // The final nil is equivalent to the ending mark NSArray * array1 = [[NSArray alloc] initWithObjects: s1, s2, s3, nil]; // The description method will be called during printing. // equivalent to: array1.descriptionNSLog (@ "% @", array1 );
We can see that the last value of his initWithObjects method is nil. We mentioned this value before. It means a null pointer, which is the same as null in Java, why is the last value empty when NSArray is created? This is similar to the scenario in C. The ending character of the string in C is '/0', so the last element of NSArray here is nil, because the NSArray Mark ends.

Then we call the NSLog method to print the NSArray object. The result is:


We can see that the formatted data is printed, because NSLog calls the description method when printing the object, which is the same as the toString method in Java, of course we can rewrite this method, which will be discussed later.

We can also use the class method to create NSArray:

// Use the class method to create array1 = [NSArray arrayWithObjects: s1, s2, s3, nil]; // create an array, put the data in the source array into NSArray * array2 = [NSArray arrayWithArray: array1];

2. Use subscript to access elements

// 2. ---------------------- objectAtIndex // access the data in the array. The array stores the NSString * str1 = [array1 objectAtIndex: 0];


3. Obtain the array size.

// 3. ---------------------- count // obtain the number of NSUInteger count = [array1 count] in the array element; // return an unsigned Value
NSUInteger is an unsigned int type.


4. Whether it contains an element

// 4. ---------------------- containsObject // determines whether the array contains an object and determines the pointer object value, not the value BOOL isContains = [array1 containsObject: @ "zhangsan"];


5. Find the subscript of an element in the array

// 5. ---------------------- indexOfObject // return the value of an object in the array NSUInteger index = [array1 indexOfObject: @ "zhangsan"]; if (index = NSNotFound) {// not found} else {// found}
Here we see a system constant NSNotFound. We can see its definition:

#define NSIntegerMax    LONG_MAX
It is the maximum value of the Long type.


6. Use the specified connector to connect all elements in the array

// 6. ---------------------- if a string is stored in the componentsJoinedByString // array, you can use a connector to connect all its elements. // note that the elements in the array must be strings NSString * content = [array1 componentsJoinedByString: @ ","];


7. Add an element at the end of the array.

// 8. ---------------------- arrayByAddingObject // append an element after the original array and return a new array object because it is an immutable NSArray * array3 = [array1 arrayByAddingObject: @ "zhaoliu"];
Because NSArray is immutable, a new NSArray object is generated and returned.


8. array Traversal

// Array traversal for (int I = 0; I <array1.count; I ++) {NSString * str = [array1 objectAtIndex: I]; NSLog (@ "% @", str);} // fast traversal for (NSString * s in array1) {NSLog (@ "% @", s );}
The second method is the same as fast traversal in Java.


9. An NSArray quick creation method is added after Xcode4.4.

// After xcode4.4, the compiler optimizes NSArray * array7 = @ [s1, s2, s3] For array creation and access syntax; NSString * s = array7 [0];
This method is faster and more convenient than the previous creation method, and complies with the normal creation method. During access, you can directly use subscript to obtain elements.


Ii. NSMutableArray class

The NSArray class is immutable, and the NSMutableArray class is variable. The same feature of the variable class is that you can perform addition, deletion, modification, and query operations.

//// Main. m // 17_NSMutableArray /// Created by jiangwei on 14-10-12. // Copyright (c) 2014 jiangwei. all rights reserved. // # import <Foundation/Foundation. h> // NSMutableArray inherits the NSArray class and has all the methods int main (int argc, const char * argv []) {@ autoreleasepool {// 1. --------------------- create a variable array NSString * str1 = @ "zhangsan"; NSString * str2 = @ "lisi"; NSString * str3 = @ "wangwu "; NSMutableArray * mArray1 = [[NSMutableArray alloc] initWithObjects: str1, str2, str3, nil]; // The following method creates an array incorrectly. // The following method creates an immutable array, you cannot create variable arrays. // NSMutableArray * array1 = @ [str1, str2, str3]; // you can create five spaces for storing elements, when more than five elements are stored, the array will automatically increase the space NSMutableArray * mArray2 = [[NSMutableArray alloc] initWithCapacity: 5]; // use the class method to create NSMutableArray * mArray3 = [NSMutableArray arrayWithCapacity: 5]; // 2. --------------------- addObject // Method for adding elements [mArray1 addObject: str1]; [mArray1 addObject: str2]; // Add an array, add all the elements in mArray1 to mArray2 [mArray2 addObjectsFromArray: mArray1]; NSLog (@ "mArray3 = % @", mArray2 ); // two-dimensional array // Add mArray1 to the mArray2 array, so that mArray2 becomes a two-dimensional array [mArray2 addObject: mArray1]; // 3. --------------------- insertObject // insert a specific element at the specified position [mArray2 insertObject: @ "def" atIndex: 0]; // 4. --------------------- replaceObjectAdIdex // replace element [mArray2 replaceObjectAtIndex: 0 withObject: @ "aaa"]; // 5. --------------------- exchangeObjectAtIndex // swap the positions of two elements [mArray2 exchangeObjectAtIndex: 0 withObjectAtIndex: 3]; // 6. --------------------- removeObjectAdIndex // Delete the element at the specified position [mArray2 removeObjectAtIndex: 0]; // Delete the last element [mArray2 removeLastObject]; // Delete the specified object [mArray2 removeObject: @ "lisi"]; // delete all objects/clear the list [mArray2 removeAllObjects];} return 0 ;}

1. Creation Method

// 1. --------------------- create a variable array NSString * str1 = @ "zhangsan"; NSString * str2 = @ "lisi"; NSString * str3 = @ "wangwu "; NSMutableArray * mArray1 = [[NSMutableArray alloc] initWithObjects: str1, str2, str3, nil]; // The following method creates an array incorrectly. // The following method creates an immutable array, cannot be used to create variable arrays. // NSMutableArray * array1 = @ [str1, str2, str3]; // you can create five spaces for storing elements, when more than five elements are stored, the array will automatically increase the space NSMutableArray * mArray2 = [[NSMutableArray alloc] initWithCapacity: 5]; // use the class method to create NSMutableArray * mArray3 = [NSMutableArray arrayWithCapacity: 5];
The creation method is similar to that of NSArray, but one method is not available, that is, the method of direct creation, which can only be used to create unchanged arrays.

However, another method of variable array is to set the size of the array in advance. After the size is exceeded, the array is automatically expanded, similar to the implementation of dynamic arrays in C language.


2. Add Elements

// 2. --------------------- addObject // Method for adding elements [mArray1 addObject: str1]; [mArray1 addObject: str2]; // Add an array, add all the elements in mArray1 to mArray2 [mArray2 addObjectsFromArray: mArray1]; NSLog (@ "mArray3 = % @", mArray2 ); // two-dimensional array // Add mArray1 to the mArray2 array, so that mArray2 becomes a two-dimensional array [mArray2 addObject: mArray1]; NSLog (@ "mArray3 = % @", mArray2 );
The addObjectsFromArray method is used to add each element in an array to the specified array.

The addObject method is used to add an array to the specified array. Then, the array is changed to a two-dimensional array.

The two methods must be differentiated ~~

The running result is as follows:



3. insert an element at the specified position of the array

// 3. --------------------- insertObject // insert a specific element at the specified position [mArray2 insertObject: @ "def" atIndex: 0];


4. Replace Elements

// 4. --------------------- replaceObjectAdIdex // replace element [mArray2 replaceObjectAtIndex: 0 withObject: @ "aaa"];

5. Swap the positions of two elements

// 5. --------------------- exchangeObjectAtIndex // place where two elements are exchanged [mArray2 exchangeObjectAtIndex: 0 withObjectAtIndex: 3];

6. Deletion Method

// 6. --------------------- removeObjectAdIndex // Delete the element at the specified position [mArray2 removeObjectAtIndex: 0]; // Delete the last element [mArray2 removeLastObject]; // Delete the specified object [mArray2 removeObject: @ "lisi"]; // delete all objects/clear the list [mArray2 removeAllObjects];


Summary

This article introduces the NSArray and NSMutableArray classes in the Foundation framework. They are used to store elements of a specified type.

Note: There is no generic concept in OC, so different types of values are stored in the array, and an error will be reported during running. Compared with Java, when operating the collection class, the security is poor. So we need to pay attention when operating the collection class.













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.